diff --git a/cmd/atlantis_generate_repo_config.go b/cmd/atlantis_generate_repo_config.go index 5bcf00b2d..0ff322dc2 100644 --- a/cmd/atlantis_generate_repo_config.go +++ b/cmd/atlantis_generate_repo_config.go @@ -20,7 +20,7 @@ var atlantisGenerateRepoConfigCmd = &cobra.Command{ err := e.ExecuteAtlantisGenerateRepoConfigCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } }, } diff --git a/cmd/aws_eks_update_kubeconfig.go b/cmd/aws_eks_update_kubeconfig.go index 51d0312cf..38363d303 100644 --- a/cmd/aws_eks_update_kubeconfig.go +++ b/cmd/aws_eks_update_kubeconfig.go @@ -15,11 +15,11 @@ var awsEksCmdUpdateKubeconfigCmd = &cobra.Command{ Long: `This command executes 'aws eks update-kubeconfig' to download 'kubeconfig' from an EKS cluster and saves it to a file. The command executes 'aws eks update-kubeconfig' in three different ways: -1. If all the required parameters (cluster name and AWS profile/role) are provided on the command-line, +1. If all the required parameters (cluster name and AWS profile/role) are provided on the command-line, then 'atmos' executes the command without requiring the 'atmos.yaml' CLI config and context. For example: atmos aws eks update-kubeconfig --profile= --name= -2. If 'component' and 'stack' are provided on the command-line, +2. If 'component' and 'stack' are provided on the command-line, then 'atmos' executes the command using the 'atmos.yaml' CLI config and stack's context by searching for the following settings: - 'components.helmfile.cluster_name_pattern' in the 'atmos.yaml' CLI config (and calculates the '--name' parameter using the pattern) - 'components.helmfile.helm_aws_profile_pattern' in the 'atmos.yaml' CLI config (and calculates the '--profile' parameter using the pattern) @@ -37,7 +37,7 @@ See https://docs.aws.amazon.com/cli/latest/reference/eks/update-kubeconfig.html Run: func(cmd *cobra.Command, args []string) { err := e.ExecuteAwsEksUpdateKubeconfigCommand(cmd, args) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } }, } diff --git a/cmd/cmd_utils.go b/cmd/cmd_utils.go index fb7569276..266cbb808 100644 --- a/cmd/cmd_utils.go +++ b/cmd/cmd_utils.go @@ -37,7 +37,7 @@ func WithStackValidation(check bool) AtmosValidateOption { // processCustomCommands processes and executes custom commands func processCustomCommands( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, commands []schema.Command, parentCommand *cobra.Command, topLevel bool, @@ -69,7 +69,7 @@ func processCustomCommands( preCustomCommand(cmd, args, parentCommand, commandConfig) }, Run: func(cmd *cobra.Command, args []string) { - executeCustomCommand(cliConfig, cmd, args, parentCommand, commandConfig) + executeCustomCommand(atmosConfig, cmd, args, parentCommand, commandConfig) }, } @@ -102,7 +102,7 @@ func processCustomCommands( command = customCommand } - err = processCustomCommands(cliConfig, commandConfig.Commands, command, false) + err = processCustomCommands(atmosConfig, commandConfig.Commands, command, false) if err != nil { return err } @@ -113,7 +113,7 @@ func processCustomCommands( // processCommandAliases processes the command aliases func processCommandAliases( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, aliases schema.CommandAliases, parentCommand *cobra.Command, topLevel bool, @@ -139,13 +139,13 @@ func processCommandAliases( Run: func(cmd *cobra.Command, args []string) { err := cmd.ParseFlags(args) if err != nil { - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } commandToRun := fmt.Sprintf("%s %s %s", os.Args[0], aliasCmd, strings.Join(args, " ")) - err = e.ExecuteShell(cliConfig, commandToRun, commandToRun, ".", nil, false) + err = e.ExecuteShell(atmosConfig, commandToRun, commandToRun, ".", nil, false) if err != nil { - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } }, } @@ -170,25 +170,25 @@ func preCustomCommand( var sb strings.Builder if len(args) != len(commandConfig.Arguments) { if len(commandConfig.Arguments) == 0 { - u.LogError(schema.CliConfiguration{}, errors.New("invalid command")) + u.LogError(schema.AtmosConfiguration{}, errors.New("invalid command")) sb.WriteString("Available command(s):\n") for i, c := range commandConfig.Commands { sb.WriteString(fmt.Sprintf("%d. %s %s %s\n", i+1, parentCommand.Use, commandConfig.Name, c.Name)) } - u.LogInfo(schema.CliConfiguration{}, sb.String()) + u.LogInfo(schema.AtmosConfiguration{}, sb.String()) os.Exit(1) } sb.WriteString(fmt.Sprintf("Command requires %d argument(s):\n", len(commandConfig.Arguments))) for i, arg := range commandConfig.Arguments { if arg.Name == "" { - u.LogErrorAndExit(schema.CliConfiguration{}, errors.New("invalid argument configuration: empty argument name")) + u.LogErrorAndExit(schema.AtmosConfiguration{}, errors.New("invalid argument configuration: empty argument name")) } sb.WriteString(fmt.Sprintf(" %d. %s\n", i+1, arg.Name)) } if len(args) > 0 { sb.WriteString(fmt.Sprintf("\nReceived %d argument(s): %s", len(args), strings.Join(args, ", "))) } - u.LogErrorAndExit(schema.CliConfiguration{}, errors.New(sb.String())) + u.LogErrorAndExit(schema.AtmosConfiguration{}, errors.New(sb.String())) } // no "steps" means a sub command should be specified @@ -211,7 +211,7 @@ func getTopLevelCommands() map[string]*cobra.Command { // executeCustomCommand executes a custom command func executeCustomCommand( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, cmd *cobra.Command, args []string, parentCommand *cobra.Command, @@ -220,7 +220,7 @@ func executeCustomCommand( var err error if commandConfig.Verbose { - cliConfig.Logs.Level = u.LogLevelTrace + atmosConfig.Logs.Level = u.LogLevelTrace } // Execute custom command's steps @@ -238,13 +238,13 @@ func executeCustomCommand( if fl.Type == "" || fl.Type == "string" { providedFlag, err := flags.GetString(fl.Name) if err != nil { - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } flagsData[fl.Name] = providedFlag } else if fl.Type == "bool" { boolFlag, err := flags.GetBool(fl.Name) if err != nil { - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } flagsData[fl.Name] = boolFlag } @@ -262,27 +262,27 @@ func executeCustomCommand( // Process Go templates in the command's 'component_config.component' component, err := e.ProcessTmpl(fmt.Sprintf("component-config-component-%d", i), commandConfig.ComponentConfig.Component, data, false) if err != nil { - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } if component == "" || component == "" { - u.LogErrorAndExit(cliConfig, fmt.Errorf("the command defines an invalid 'component_config.component: %s' in '%s'", + u.LogErrorAndExit(atmosConfig, fmt.Errorf("the command defines an invalid 'component_config.component: %s' in '%s'", commandConfig.ComponentConfig.Component, cfg.CliConfigFileName+u.DefaultStackConfigFileExtension)) } // Process Go templates in the command's 'component_config.stack' stack, err := e.ProcessTmpl(fmt.Sprintf("component-config-stack-%d", i), commandConfig.ComponentConfig.Stack, data, false) if err != nil { - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } if stack == "" || stack == "" { - u.LogErrorAndExit(cliConfig, fmt.Errorf("the command defines an invalid 'component_config.stack: %s' in '%s'", + u.LogErrorAndExit(atmosConfig, fmt.Errorf("the command defines an invalid 'component_config.stack: %s' in '%s'", commandConfig.ComponentConfig.Stack, cfg.CliConfigFileName+u.DefaultStackConfigFileExtension)) } // Get the config for the component in the stack componentConfig, err := e.ExecuteDescribeComponent(component, stack, true) if err != nil { - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } data["ComponentConfig"] = componentConfig } @@ -299,36 +299,36 @@ func executeCustomCommand( err = fmt.Errorf("either 'value' or 'valueCommand' can be specified for the ENV var, but not both.\n"+ "Custom command '%s %s' defines 'value=%s' and 'valueCommand=%s' for the ENV var '%s'", parentCommand.Name(), commandConfig.Name, value, valCommand, key) - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } // If the command to get the value for the ENV var is provided, execute it if valCommand != "" { valCommandName := fmt.Sprintf("env-var-%s-valcommand", key) - res, err := e.ExecuteShellAndReturnOutput(cliConfig, valCommand, valCommandName, ".", nil, false) + res, err := e.ExecuteShellAndReturnOutput(atmosConfig, valCommand, valCommandName, ".", nil, false) if err != nil { - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } value = strings.TrimRight(res, "\r\n") } else { // Process Go templates in the values of the command's ENV vars value, err = e.ProcessTmpl(fmt.Sprintf("env-var-%d", i), value, data, false) if err != nil { - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } } envVarsList = append(envVarsList, fmt.Sprintf("%s=%s", key, value)) err = os.Setenv(key, value) if err != nil { - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } } if len(envVarsList) > 0 && commandConfig.Verbose { - u.LogDebug(cliConfig, "\nUsing ENV vars:") + u.LogDebug(atmosConfig, "\nUsing ENV vars:") for _, v := range envVarsList { - u.LogDebug(cliConfig, v) + u.LogDebug(atmosConfig, v) } } @@ -336,14 +336,14 @@ func executeCustomCommand( // Steps support Go templates and have access to {{ .ComponentConfig.xxx.yyy.zzz }} Go template variables commandToRun, err := e.ProcessTmpl(fmt.Sprintf("step-%d", i), step, data, false) if err != nil { - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } // Execute the command step commandName := fmt.Sprintf("%s-step-%d", commandConfig.Name, i) - err = e.ExecuteShell(cliConfig, commandToRun, commandName, ".", envVarsList, false) + err = e.ExecuteShell(atmosConfig, commandToRun, commandName, ".", envVarsList, false) if err != nil { - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } } } @@ -374,43 +374,43 @@ func checkAtmosConfig(opts ...AtmosValidateOption) { opt(vCfg) } - cliConfig, err := cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, false) + atmosConfig, err := cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, false) if err != nil { - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } if vCfg.CheckStack { - atmosConfigExists, err := u.IsDirectory(cliConfig.StacksBaseAbsolutePath) + atmosConfigExists, err := u.IsDirectory(atmosConfig.StacksBaseAbsolutePath) if !atmosConfigExists || err != nil { - printMessageForMissingAtmosConfig(cliConfig) + printMessageForMissingAtmosConfig(atmosConfig) os.Exit(0) } } } // printMessageForMissingAtmosConfig prints Atmos logo and instructions on how to configure and start using Atmos -func printMessageForMissingAtmosConfig(cliConfig schema.CliConfiguration) { +func printMessageForMissingAtmosConfig(atmosConfig schema.AtmosConfiguration) { c1 := color.New(color.FgCyan) c2 := color.New(color.FgGreen) fmt.Println() err := tuiUtils.PrintStyledText("ATMOS") if err != nil { - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } - if cliConfig.Default { + if atmosConfig.Default { // If Atmos did not find an `atmos.yaml` config file and is using the default config u.PrintMessageInColor("atmos.yaml", c1) fmt.Println(" CLI config file was not found.") fmt.Print("\nThe default Atmos stacks directory is set to ") - u.PrintMessageInColor(filepath.Join(cliConfig.BasePath, cliConfig.Stacks.BasePath), c1) + u.PrintMessageInColor(filepath.Join(atmosConfig.BasePath, atmosConfig.Stacks.BasePath), c1) fmt.Println(",\nbut the directory does not exist in the current path.") } else { // If Atmos found an `atmos.yaml` config file, but it defines invalid paths to Atmos stacks and components u.PrintMessageInColor("atmos.yaml", c1) fmt.Print(" CLI config file specifies the directory for Atmos stacks as ") - u.PrintMessageInColor(filepath.Join(cliConfig.BasePath, cliConfig.Stacks.BasePath), c1) + u.PrintMessageInColor(filepath.Join(atmosConfig.BasePath, atmosConfig.Stacks.BasePath), c1) fmt.Println(",\nbut the directory does not exist.") } @@ -432,21 +432,21 @@ func printMessageForMissingAtmosConfig(cliConfig schema.CliConfiguration) { // CheckForAtmosUpdateAndPrintMessage checks if a version update is needed and prints a message if a newer version is found. // It loads the cache, decides if it's time to check for updates, compares the current version to the latest available release, // and if newer, prints the update message. It also updates the cache's timestamp after printing. -func CheckForAtmosUpdateAndPrintMessage(cliConfig schema.CliConfiguration) { +func CheckForAtmosUpdateAndPrintMessage(atmosConfig schema.AtmosConfiguration) { // If version checking is disabled in the configuration, do nothing - if !cliConfig.Version.Check.Enabled { + if !atmosConfig.Version.Check.Enabled { return } // Load the cache cacheCfg, err := cfg.LoadCache() if err != nil { - u.LogWarning(cliConfig, fmt.Sprintf("Could not load cache: %s", err)) + u.LogWarning(atmosConfig, fmt.Sprintf("Could not load cache: %s", err)) return } // Determine if it's time to check for updates based on frequency and last_checked - if !cfg.ShouldCheckForUpdates(cacheCfg.LastChecked, cliConfig.Version.Check.Frequency) { + if !cfg.ShouldCheckForUpdates(cacheCfg.LastChecked, atmosConfig.Version.Check.Frequency) { // Not due for another check yet, so return without printing anything return } @@ -454,12 +454,12 @@ func CheckForAtmosUpdateAndPrintMessage(cliConfig schema.CliConfiguration) { // Get the latest Atmos release from GitHub latestReleaseTag, err := u.GetLatestGitHubRepoRelease("cloudposse", "atmos") if err != nil { - u.LogWarning(cliConfig, fmt.Sprintf("Failed to retrieve latest Atmos release info: %s", err)) + u.LogWarning(atmosConfig, fmt.Sprintf("Failed to retrieve latest Atmos release info: %s", err)) return } if latestReleaseTag == "" { - u.LogWarning(cliConfig, "No release information available") + u.LogWarning(atmosConfig, "No release information available") return } @@ -475,14 +475,14 @@ func CheckForAtmosUpdateAndPrintMessage(cliConfig schema.CliConfiguration) { // Update the cache to mark the current timestamp cacheCfg.LastChecked = time.Now().Unix() if saveErr := cfg.SaveCache(cacheCfg); saveErr != nil { - u.LogWarning(cliConfig, fmt.Sprintf("Unable to save cache: %s", saveErr)) + u.LogWarning(atmosConfig, fmt.Sprintf("Unable to save cache: %s", saveErr)) } } func customHelpMessageToUpgradeToAtmosLatestRelease(cmd *cobra.Command, args []string) { originalHelpFunc(cmd, args) - CheckForAtmosUpdateAndPrintMessage(cliConfig) + CheckForAtmosUpdateAndPrintMessage(atmosConfig) } // Check Atmos is version command diff --git a/cmd/completion.go b/cmd/completion.go index cde9287df..ab74194d1 100644 --- a/cmd/completion.go +++ b/cmd/completion.go @@ -1,9 +1,10 @@ package cmd import ( - "github.com/cloudposse/atmos/pkg/schema" "os" + "github.com/cloudposse/atmos/pkg/schema" + "github.com/spf13/cobra" u "github.com/cloudposse/atmos/pkg/utils" @@ -31,7 +32,7 @@ var completionCmd = &cobra.Command{ } if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } }, } diff --git a/cmd/describe_affected.go b/cmd/describe_affected.go index 815aa1801..df05090a7 100644 --- a/cmd/describe_affected.go +++ b/cmd/describe_affected.go @@ -20,7 +20,7 @@ var describeAffectedCmd = &cobra.Command{ err := e.ExecuteDescribeAffectedCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } }, } diff --git a/cmd/describe_component.go b/cmd/describe_component.go index 4ae3cc9fe..b40de68cd 100644 --- a/cmd/describe_component.go +++ b/cmd/describe_component.go @@ -20,7 +20,7 @@ var describeComponentCmd = &cobra.Command{ err := e.ExecuteDescribeComponentCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } }, } @@ -34,7 +34,7 @@ func init() { err := describeComponentCmd.MarkPersistentFlagRequired("stack") if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } describeCmd.AddCommand(describeComponentCmd) diff --git a/cmd/describe_config.go b/cmd/describe_config.go index 87fead79a..3f201ee9f 100644 --- a/cmd/describe_config.go +++ b/cmd/describe_config.go @@ -17,7 +17,7 @@ var describeConfigCmd = &cobra.Command{ Run: func(cmd *cobra.Command, args []string) { err := e.ExecuteDescribeConfigCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } }, } diff --git a/cmd/describe_dependents.go b/cmd/describe_dependents.go index 94e384c4c..bad419954 100644 --- a/cmd/describe_dependents.go +++ b/cmd/describe_dependents.go @@ -21,7 +21,7 @@ var describeDependentsCmd = &cobra.Command{ err := e.ExecuteDescribeDependentsCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } }, } @@ -35,7 +35,7 @@ func init() { err := describeDependentsCmd.MarkPersistentFlagRequired("stack") if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } describeCmd.AddCommand(describeDependentsCmd) diff --git a/cmd/describe_stacks.go b/cmd/describe_stacks.go index 8b6d87fb1..6cf497739 100644 --- a/cmd/describe_stacks.go +++ b/cmd/describe_stacks.go @@ -20,7 +20,7 @@ var describeStacksCmd = &cobra.Command{ err := e.ExecuteDescribeStacksCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } }, } diff --git a/cmd/describe_workflows.go b/cmd/describe_workflows.go index 4e8e1020b..fe644155c 100644 --- a/cmd/describe_workflows.go +++ b/cmd/describe_workflows.go @@ -24,7 +24,7 @@ var describeWorkflowsCmd = &cobra.Command{ Run: func(cmd *cobra.Command, args []string) { err := e.ExecuteDescribeWorkflowsCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } }, } diff --git a/cmd/docs.go b/cmd/docs.go index 29af42b6e..650a74d25 100644 --- a/cmd/docs.go +++ b/cmd/docs.go @@ -34,14 +34,14 @@ var docsCmd = &cobra.Command{ ComponentFolderPrefix: "terraform", } - cliConfig, err := cfg.InitCliConfig(info, true) + atmosConfig, err := cfg.InitCliConfig(info, true) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } // Detect terminal width if not specified in `atmos.yaml` // The default screen width is 120 characters, but uses maxWidth if set and greater than zero - maxWidth := cliConfig.Settings.Docs.MaxWidth + maxWidth := atmosConfig.Settings.Docs.MaxWidth defaultWidth := 120 screenWidth := defaultWidth @@ -59,27 +59,27 @@ var docsCmd = &cobra.Command{ } // Construct the full path to the Terraform component by combining the Atmos base path, Terraform base path, and component name - componentPath := filepath.Join(cliConfig.BasePath, cliConfig.Components.Terraform.BasePath, info.Component) + componentPath := filepath.Join(atmosConfig.BasePath, atmosConfig.Components.Terraform.BasePath, info.Component) componentPathExists, err := u.IsDirectory(componentPath) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } if !componentPathExists { - u.LogErrorAndExit(schema.CliConfiguration{}, fmt.Errorf("Component '%s' not found in path: '%s'", info.Component, componentPath)) + u.LogErrorAndExit(schema.AtmosConfiguration{}, fmt.Errorf("Component '%s' not found in path: '%s'", info.Component, componentPath)) } readmePath := filepath.Join(componentPath, "README.md") if _, err := os.Stat(readmePath); err != nil { if os.IsNotExist(err) { - u.LogErrorAndExit(schema.CliConfiguration{}, fmt.Errorf("No README found for component: %s", info.Component)) + u.LogErrorAndExit(schema.AtmosConfiguration{}, fmt.Errorf("No README found for component: %s", info.Component)) } else { - u.LogErrorAndExit(schema.CliConfiguration{}, fmt.Errorf("Component %s not found", info.Component)) + u.LogErrorAndExit(schema.AtmosConfiguration{}, fmt.Errorf("Component %s not found", info.Component)) } } readmeContent, err := os.ReadFile(readmePath) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } r, err := glamour.NewTermRenderer( @@ -89,16 +89,16 @@ var docsCmd = &cobra.Command{ glamour.WithWordWrap(screenWidth), ) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, fmt.Errorf("failed to initialize markdown renderer: %w", err)) + u.LogErrorAndExit(schema.AtmosConfiguration{}, fmt.Errorf("failed to initialize markdown renderer: %w", err)) } componentDocs, err := r.Render(string(readmeContent)) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } - if err := u.DisplayDocs(componentDocs, cliConfig.Settings.Docs.Pagination); err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, fmt.Errorf("failed to display documentation: %w", err)) + if err := u.DisplayDocs(componentDocs, atmosConfig.Settings.Docs.Pagination); err != nil { + u.LogErrorAndExit(schema.AtmosConfiguration{}, fmt.Errorf("failed to display documentation: %w", err)) } return @@ -118,7 +118,7 @@ var docsCmd = &cobra.Command{ } if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } }, } diff --git a/cmd/helmfile.go b/cmd/helmfile.go index d2236e835..8bd20dbde 100644 --- a/cmd/helmfile.go +++ b/cmd/helmfile.go @@ -29,12 +29,12 @@ var helmfileCmd = &cobra.Command{ info, err := e.ProcessCommandLineArgs("helmfile", cmd, finalArgs, argsAfterDoubleDash) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } // Exit on help if info.NeedHelp { // Check for the latest Atmos release on GitHub and print update message - CheckForAtmosUpdateAndPrintMessage(cliConfig) + CheckForAtmosUpdateAndPrintMessage(atmosConfig) return } // Check Atmos configuration @@ -42,7 +42,7 @@ var helmfileCmd = &cobra.Command{ err = e.ExecuteHelmfile(info) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } }, } diff --git a/cmd/helmfile_generate_varfile.go b/cmd/helmfile_generate_varfile.go index 57f8a66d5..0d04b6207 100644 --- a/cmd/helmfile_generate_varfile.go +++ b/cmd/helmfile_generate_varfile.go @@ -20,7 +20,7 @@ var helmfileGenerateVarfileCmd = &cobra.Command{ err := e.ExecuteHelmfileGenerateVarfileCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } }, } @@ -32,7 +32,7 @@ func init() { err := helmfileGenerateVarfileCmd.MarkPersistentFlagRequired("stack") if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } helmfileGenerateCmd.AddCommand(helmfileGenerateVarfileCmd) diff --git a/cmd/list_components.go b/cmd/list_components.go index 03cf6feff..cce734c28 100644 --- a/cmd/list_components.go +++ b/cmd/list_components.go @@ -26,13 +26,13 @@ var listComponentsCmd = &cobra.Command{ stackFlag, _ := cmd.Flags().GetString("stack") configAndStacksInfo := schema.ConfigAndStacksInfo{} - cliConfig, err := config.InitCliConfig(configAndStacksInfo, true) + atmosConfig, err := config.InitCliConfig(configAndStacksInfo, true) if err != nil { u.PrintMessageInColor(fmt.Sprintf("Error initializing CLI config: %v", err), color.New(color.FgRed)) return } - stacksMap, err := e.ExecuteDescribeStacks(cliConfig, "", nil, nil, nil, false, false, false) + stacksMap, err := e.ExecuteDescribeStacks(atmosConfig, "", nil, nil, nil, false, false, false) if err != nil { u.PrintMessageInColor(fmt.Sprintf("Error describing stacks: %v", err), color.New(color.FgRed)) return diff --git a/cmd/list_stacks.go b/cmd/list_stacks.go index 38d5e547e..1ce6c3f61 100644 --- a/cmd/list_stacks.go +++ b/cmd/list_stacks.go @@ -27,13 +27,13 @@ var listStacksCmd = &cobra.Command{ componentFlag, _ := cmd.Flags().GetString("component") configAndStacksInfo := schema.ConfigAndStacksInfo{} - cliConfig, err := config.InitCliConfig(configAndStacksInfo, true) + atmosConfig, err := config.InitCliConfig(configAndStacksInfo, true) if err != nil { u.PrintMessageInColor(fmt.Sprintf("Error initializing CLI config: %v", err), color.New(color.FgRed)) return } - stacksMap, err := e.ExecuteDescribeStacks(cliConfig, "", nil, nil, nil, false, false, false) + stacksMap, err := e.ExecuteDescribeStacks(atmosConfig, "", nil, nil, nil, false, false, false) if err != nil { u.PrintMessageInColor(fmt.Sprintf("Error describing stacks: %v", err), color.New(color.FgRed)) return diff --git a/cmd/pro_lock.go b/cmd/pro_lock.go index 1fde9ed7e..fc37aaa90 100644 --- a/cmd/pro_lock.go +++ b/cmd/pro_lock.go @@ -20,7 +20,7 @@ var proLockCmd = &cobra.Command{ err := e.ExecuteProLockCommand(cmd, args) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } }, } diff --git a/cmd/pro_unlock.go b/cmd/pro_unlock.go index e8176240e..b612306cd 100644 --- a/cmd/pro_unlock.go +++ b/cmd/pro_unlock.go @@ -20,7 +20,7 @@ var proUnlockCmd = &cobra.Command{ err := e.ExecuteProUnlockCommand(cmd, args) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } }, } diff --git a/cmd/root.go b/cmd/root.go index c7b043a3f..93eb820e0 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -18,7 +18,7 @@ import ( u "github.com/cloudposse/atmos/pkg/utils" ) -var cliConfig schema.CliConfiguration +var atmosConfig schema.AtmosConfiguration // originalHelpFunc holds Cobra's original help function to avoid recursion. var originalHelpFunc func(*cobra.Command, []string) @@ -52,12 +52,12 @@ var RootCmd = &cobra.Command{ fmt.Println() err := tuiUtils.PrintStyledText("ATMOS") if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } err = e.ExecuteAtmosCmd() if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } }, } @@ -80,19 +80,19 @@ func Execute() error { fmt.Println() err = tuiUtils.PrintStyledText("ATMOS") if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } } // InitCliConfig finds and merges CLI configurations in the following order: // system dir, home dir, current dir, ENV vars, command-line arguments // Here we need the custom commands from the config var initErr error - cliConfig, initErr = cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, false) + atmosConfig, initErr = cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, false) if initErr != nil && !errors.Is(initErr, cfg.NotFound) { if isVersionCommand() { - u.LogTrace(schema.CliConfiguration{}, fmt.Sprintf("warning: CLI configuration 'atmos.yaml' file not found. Error: %s", initErr)) + u.LogTrace(schema.AtmosConfiguration{}, fmt.Sprintf("warning: CLI configuration 'atmos.yaml' file not found. Error: %s", initErr)) } else { - u.LogErrorAndExit(schema.CliConfiguration{}, initErr) + u.LogErrorAndExit(schema.AtmosConfiguration{}, initErr) } } @@ -106,14 +106,14 @@ func Execute() error { // If CLI configuration was found, process its custom commands and command aliases if initErr == nil { - err = processCustomCommands(cliConfig, cliConfig.Commands, RootCmd, true) + err = processCustomCommands(atmosConfig, atmosConfig.Commands, RootCmd, true) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } - err = processCommandAliases(cliConfig, cliConfig.CommandAliases, RootCmd, true) + err = processCommandAliases(atmosConfig, atmosConfig.CommandAliases, RootCmd, true) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } } @@ -146,7 +146,7 @@ func initConfig() { fmt.Println() err := tuiUtils.PrintStyledText("ATMOS") if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } b.HelpFunc(command, strings) diff --git a/cmd/terraform.go b/cmd/terraform.go index 586e79d22..dfd5ea610 100644 --- a/cmd/terraform.go +++ b/cmd/terraform.go @@ -30,13 +30,13 @@ var terraformCmd = &cobra.Command{ } info, err := e.ProcessCommandLineArgs("terraform", cmd, finalArgs, argsAfterDoubleDash) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } // Exit on help if info.NeedHelp { // Check for the latest Atmos release on GitHub and print update message - CheckForAtmosUpdateAndPrintMessage(cliConfig) + CheckForAtmosUpdateAndPrintMessage(atmosConfig) return } // Check Atmos configuration @@ -44,7 +44,7 @@ var terraformCmd = &cobra.Command{ err = e.ExecuteTerraform(info) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } }, } diff --git a/cmd/terraform_generate_backend.go b/cmd/terraform_generate_backend.go index 4912aee2c..823d32bd6 100644 --- a/cmd/terraform_generate_backend.go +++ b/cmd/terraform_generate_backend.go @@ -20,7 +20,7 @@ var terraformGenerateBackendCmd = &cobra.Command{ err := e.ExecuteTerraformGenerateBackendCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } }, } @@ -31,7 +31,7 @@ func init() { err := terraformGenerateBackendCmd.MarkPersistentFlagRequired("stack") if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } terraformGenerateCmd.AddCommand(terraformGenerateBackendCmd) diff --git a/cmd/terraform_generate_backends.go b/cmd/terraform_generate_backends.go index 3c80fedb2..ee7aff947 100644 --- a/cmd/terraform_generate_backends.go +++ b/cmd/terraform_generate_backends.go @@ -20,7 +20,7 @@ var terraformGenerateBackendsCmd = &cobra.Command{ err := e.ExecuteTerraformGenerateBackendsCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } }, } diff --git a/cmd/terraform_generate_varfile.go b/cmd/terraform_generate_varfile.go index c82ac14b8..7cf5f6b17 100644 --- a/cmd/terraform_generate_varfile.go +++ b/cmd/terraform_generate_varfile.go @@ -20,7 +20,7 @@ var terraformGenerateVarfileCmd = &cobra.Command{ err := e.ExecuteTerraformGenerateVarfileCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } }, } @@ -32,7 +32,7 @@ func init() { err := terraformGenerateVarfileCmd.MarkPersistentFlagRequired("stack") if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } terraformGenerateCmd.AddCommand(terraformGenerateVarfileCmd) diff --git a/cmd/terraform_generate_varfiles.go b/cmd/terraform_generate_varfiles.go index 1031fbb2f..c41708c05 100644 --- a/cmd/terraform_generate_varfiles.go +++ b/cmd/terraform_generate_varfiles.go @@ -20,7 +20,7 @@ var terraformGenerateVarfilesCmd = &cobra.Command{ err := e.ExecuteTerraformGenerateVarfilesCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } }, } @@ -58,7 +58,7 @@ func init() { err := terraformGenerateVarfilesCmd.MarkPersistentFlagRequired("file-template") if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } terraformGenerateCmd.AddCommand(terraformGenerateVarfilesCmd) diff --git a/cmd/validate_component.go b/cmd/validate_component.go index 9b2980cbd..8c68fb866 100644 --- a/cmd/validate_component.go +++ b/cmd/validate_component.go @@ -26,7 +26,7 @@ var validateComponentCmd = &cobra.Command{ component, stack, err := e.ExecuteValidateComponentCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } m := fmt.Sprintf("component '%s' in stack '%s' validated successfully\n", component, stack) @@ -45,7 +45,7 @@ func init() { err := validateComponentCmd.MarkPersistentFlagRequired("stack") if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } validateCmd.AddCommand(validateComponentCmd) diff --git a/cmd/validate_stacks.go b/cmd/validate_stacks.go index d38ff01ad..ab8cb92d3 100644 --- a/cmd/validate_stacks.go +++ b/cmd/validate_stacks.go @@ -22,7 +22,7 @@ var ValidateStacksCmd = &cobra.Command{ err := e.ExecuteValidateStacksCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } u.PrintMessageInColor("all stacks validated successfully\n", color.New(color.FgGreen)) diff --git a/cmd/vendor_diff.go b/cmd/vendor_diff.go index 61cad8771..a9bbf17de 100644 --- a/cmd/vendor_diff.go +++ b/cmd/vendor_diff.go @@ -20,7 +20,7 @@ var vendorDiffCmd = &cobra.Command{ err := e.ExecuteVendorDiffCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } }, } diff --git a/cmd/vendor_pull.go b/cmd/vendor_pull.go index b616d365d..20bab4490 100644 --- a/cmd/vendor_pull.go +++ b/cmd/vendor_pull.go @@ -21,7 +21,7 @@ var vendorPullCmd = &cobra.Command{ err := e.ExecuteVendorPullCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } }, } diff --git a/cmd/version.go b/cmd/version.go index c865d81d0..f188fdc34 100644 --- a/cmd/version.go +++ b/cmd/version.go @@ -25,7 +25,7 @@ var versionCmd = &cobra.Command{ fmt.Println() err := tuiUtils.PrintStyledText("ATMOS") if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } u.PrintMessage(fmt.Sprintf("\U0001F47D Atmos %s on %s/%s", version.Version, runtime.GOOS, runtime.GOARCH)) @@ -36,11 +36,11 @@ var versionCmd = &cobra.Command{ latestReleaseTag, err := u.GetLatestGitHubRepoRelease("cloudposse", "atmos") if err == nil && latestReleaseTag != "" { if err != nil { - u.LogWarning(schema.CliConfiguration{}, fmt.Sprintf("Failed to check for updates: %v", err)) + u.LogWarning(schema.AtmosConfiguration{}, fmt.Sprintf("Failed to check for updates: %v", err)) return } if latestReleaseTag == "" { - u.LogWarning(schema.CliConfiguration{}, "No release information available") + u.LogWarning(schema.AtmosConfiguration{}, "No release information available") return } latestRelease := strings.TrimPrefix(latestReleaseTag, "v") @@ -53,7 +53,7 @@ var versionCmd = &cobra.Command{ } // Check for the cache and print update message - CheckForAtmosUpdateAndPrintMessage(cliConfig) + CheckForAtmosUpdateAndPrintMessage(atmosConfig) }, } diff --git a/cmd/workflow.go b/cmd/workflow.go index 206382eed..cc657a6c9 100644 --- a/cmd/workflow.go +++ b/cmd/workflow.go @@ -24,7 +24,7 @@ var workflowCmd = &cobra.Command{ Run: func(cmd *cobra.Command, args []string) { err := e.ExecuteWorkflowCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } }, } diff --git a/internal/exec/atlantis_generate_repo_config.go b/internal/exec/atlantis_generate_repo_config.go index c1f0a2c87..d833740e9 100644 --- a/internal/exec/atlantis_generate_repo_config.go +++ b/internal/exec/atlantis_generate_repo_config.go @@ -23,7 +23,7 @@ func ExecuteAtlantisGenerateRepoConfigCmd(cmd *cobra.Command, args []string) err return err } - cliConfig, err := cfg.InitCliConfig(info, true) + atmosConfig, err := cfg.InitCliConfig(info, true) if err != nil { return err } @@ -106,7 +106,7 @@ func ExecuteAtlantisGenerateRepoConfigCmd(cmd *cobra.Command, args []string) err } return ExecuteAtlantisGenerateRepoConfigAffectedOnly( - cliConfig, + atmosConfig, outputPath, configTemplateName, projectTemplateName, @@ -122,7 +122,7 @@ func ExecuteAtlantisGenerateRepoConfigCmd(cmd *cobra.Command, args []string) err } return ExecuteAtlantisGenerateRepoConfig( - cliConfig, + atmosConfig, outputPath, configTemplateName, projectTemplateName, @@ -133,7 +133,7 @@ func ExecuteAtlantisGenerateRepoConfigCmd(cmd *cobra.Command, args []string) err // ExecuteAtlantisGenerateRepoConfigAffectedOnly generates repository configuration for Atlantis only for the affected components and stacks func ExecuteAtlantisGenerateRepoConfigAffectedOnly( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, outputPath string, configTemplateName string, projectTemplateName string, @@ -155,7 +155,7 @@ func ExecuteAtlantisGenerateRepoConfigAffectedOnly( if repoPath != "" { affected, _, _, _, err = ExecuteDescribeAffectedWithTargetRepoPath( - cliConfig, + atmosConfig, repoPath, verbose, false, @@ -164,7 +164,7 @@ func ExecuteAtlantisGenerateRepoConfigAffectedOnly( ) } else if cloneTargetRef { affected, _, _, _, err = ExecuteDescribeAffectedWithTargetRefClone( - cliConfig, + atmosConfig, ref, sha, sshKeyPath, @@ -176,7 +176,7 @@ func ExecuteAtlantisGenerateRepoConfigAffectedOnly( ) } else { affected, _, _, _, err = ExecuteDescribeAffectedWithTargetRefCheckout( - cliConfig, + atmosConfig, ref, sha, verbose, @@ -209,7 +209,7 @@ func ExecuteAtlantisGenerateRepoConfigAffectedOnly( }) return ExecuteAtlantisGenerateRepoConfig( - cliConfig, + atmosConfig, outputPath, configTemplateName, projectTemplateName, @@ -220,7 +220,7 @@ func ExecuteAtlantisGenerateRepoConfigAffectedOnly( // ExecuteAtlantisGenerateRepoConfig generates repository configuration for Atlantis func ExecuteAtlantisGenerateRepoConfig( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, outputPath string, configTemplateNameArg string, projectTemplateNameArg string, @@ -228,7 +228,7 @@ func ExecuteAtlantisGenerateRepoConfig( components []string, ) error { - stacksMap, _, err := FindStacksMap(cliConfig, false) + stacksMap, _, err := FindStacksMap(atmosConfig, false) if err != nil { return err } @@ -244,7 +244,7 @@ func ExecuteAtlantisGenerateRepoConfig( var settingsSection map[string]any if projectTemplateNameArg != "" { - if projectTemplate, ok = cliConfig.Integrations.Atlantis.ProjectTemplates[projectTemplateNameArg]; !ok { + if projectTemplate, ok = atmosConfig.Integrations.Atlantis.ProjectTemplates[projectTemplateNameArg]; !ok { return errors.Errorf("atlantis project template '%s' is not defined in 'integrations.atlantis.project_templates' in 'atmos.yaml'", projectTemplateNameArg) } } @@ -305,7 +305,7 @@ func ExecuteAtlantisGenerateRepoConfig( return err } } else if settingsAtlantisProjectTemplateName, ok := settingsAtlantisSection["project_template_name"].(string); ok && settingsAtlantisProjectTemplateName != "" { - if projectTemplate, ok = cliConfig.Integrations.Atlantis.ProjectTemplates[settingsAtlantisProjectTemplateName]; !ok { + if projectTemplate, ok = atmosConfig.Integrations.Atlantis.ProjectTemplates[settingsAtlantisProjectTemplateName]; !ok { return errors.Errorf( "the component '%s' in the stack config file '%s' "+ "specifies the atlantis project template name '%s' "+ @@ -339,8 +339,8 @@ func ExecuteAtlantisGenerateRepoConfig( // Absolute path to the terraform component terraformComponentPath := filepath.Join( - cliConfig.BasePath, - cliConfig.Components.Terraform.BasePath, + atmosConfig.BasePath, + atmosConfig.Components.Terraform.BasePath, terraformComponent, ) @@ -348,7 +348,7 @@ func ExecuteAtlantisGenerateRepoConfig( context := cfg.GetContextFromVars(varsSection) context.Component = strings.Replace(componentName, "/", "-", -1) context.ComponentPath = terraformComponentPath - contextPrefix, err := cfg.GetContextPrefix(stackConfigFileName, context, GetStackNamePattern(cliConfig), stackConfigFileName) + contextPrefix, err := cfg.GetContextPrefix(stackConfigFileName, context, GetStackNamePattern(atmosConfig), stackConfigFileName) if err != nil { return err } @@ -373,7 +373,7 @@ func ExecuteAtlantisGenerateRepoConfig( } // Calculate terraform workspace - workspace, err := BuildTerraformWorkspace(cliConfig, configAndStacksInfo) + workspace, err := BuildTerraformWorkspace(atmosConfig, configAndStacksInfo) if err != nil { return err } @@ -433,7 +433,7 @@ func ExecuteAtlantisGenerateRepoConfig( return err } } else if settingsAtlantisConfigTemplateName, ok := settingsAtlantisSection["config_template_name"].(string); ok && settingsAtlantisConfigTemplateName != "" { - if configTemplate, ok = cliConfig.Integrations.Atlantis.ConfigTemplates[settingsAtlantisConfigTemplateName]; !ok { + if configTemplate, ok = atmosConfig.Integrations.Atlantis.ConfigTemplates[settingsAtlantisConfigTemplateName]; !ok { return errors.Errorf( "atlantis config template name '%s' is specified "+ "in the 'settings.atlantis.config_template_name' section, "+ @@ -444,7 +444,7 @@ func ExecuteAtlantisGenerateRepoConfig( } } } else { - if configTemplate, ok = cliConfig.Integrations.Atlantis.ConfigTemplates[configTemplateNameArg]; !ok { + if configTemplate, ok = atmosConfig.Integrations.Atlantis.ConfigTemplates[configTemplateNameArg]; !ok { return errors.Errorf("atlantis config template '%s' is not defined in 'integrations.atlantis.config_templates' in 'atmos.yaml'", configTemplateNameArg) } } @@ -477,8 +477,8 @@ func ExecuteAtlantisGenerateRepoConfig( } } - if reflect.ValueOf(atlantisYaml.Workflows).IsZero() && !reflect.ValueOf(cliConfig.Integrations.Atlantis.WorkflowTemplates).IsZero() { - atlantisYaml.Workflows = cliConfig.Integrations.Atlantis.WorkflowTemplates + if reflect.ValueOf(atlantisYaml.Workflows).IsZero() && !reflect.ValueOf(atmosConfig.Integrations.Atlantis.WorkflowTemplates).IsZero() { + atlantisYaml.Workflows = atmosConfig.Integrations.Atlantis.WorkflowTemplates } // Write the atlantis config to a file at the specified path @@ -486,15 +486,15 @@ func ExecuteAtlantisGenerateRepoConfig( // Then check the 'atlantis.path' setting in 'atmos.yaml' fileName := outputPath if fileName == "" { - fileName = cliConfig.Integrations.Atlantis.Path - u.LogDebug(cliConfig, fmt.Sprintf("Using 'atlantis.path: %s' from 'atmos.yaml'", fileName)) + fileName = atmosConfig.Integrations.Atlantis.Path + u.LogDebug(atmosConfig, fmt.Sprintf("Using 'atlantis.path: %s' from 'atmos.yaml'", fileName)) } else { - u.LogDebug(cliConfig, fmt.Sprintf("Using '--output-path %s' command-line argument", fileName)) + u.LogDebug(atmosConfig, fmt.Sprintf("Using '--output-path %s' command-line argument", fileName)) } // If the path is empty, dump to 'stdout' if fileName != "" { - u.LogDebug(cliConfig, fmt.Sprintf("Writing atlantis repo config file to '%s'\n", fileName)) + u.LogDebug(atmosConfig, fmt.Sprintf("Writing atlantis repo config file to '%s'\n", fileName)) fileAbsolutePath, err := filepath.Abs(fileName) if err != nil { diff --git a/internal/exec/atlantis_utils.go b/internal/exec/atlantis_utils.go index 1b81ad542..46a8b08a9 100644 --- a/internal/exec/atlantis_utils.go +++ b/internal/exec/atlantis_utils.go @@ -12,7 +12,7 @@ import ( // BuildAtlantisProjectNameFromComponentConfig builds an Atlantis project name from the component config func BuildAtlantisProjectNameFromComponentConfig( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, configAndStacksInfo schema.ConfigAndStacksInfo, ) (string, error) { @@ -27,7 +27,7 @@ func BuildAtlantisProjectNameFromComponentConfig( return "", err } } else if atlantisSettingsProjectTemplateName, ok := atlantisSettingsSection["project_template_name"].(string); ok && atlantisSettingsProjectTemplateName != "" { - if pt, ok := cliConfig.Integrations.Atlantis.ProjectTemplates[atlantisSettingsProjectTemplateName]; ok { + if pt, ok := atmosConfig.Integrations.Atlantis.ProjectTemplates[atlantisSettingsProjectTemplateName]; ok { atlantisProjectTemplate = pt } } diff --git a/internal/exec/atmos.go b/internal/exec/atmos.go index a7f5f6f7d..9da19bf54 100644 --- a/internal/exec/atmos.go +++ b/internal/exec/atmos.go @@ -34,14 +34,14 @@ func ExecuteAtmosCmd() error { } configAndStacksInfo := schema.ConfigAndStacksInfo{} - cliConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) + atmosConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) if err != nil { return err } // Get a map of stacks and components in the stacks // Don't process `Go` templates in Atmos stack manifests since we just need to display the stack and component names in the TUI - stacksMap, err := ExecuteDescribeStacks(cliConfig, "", nil, nil, nil, false, false, false) + stacksMap, err := ExecuteDescribeStacks(atmosConfig, "", nil, nil, nil, false, false, false) if err != nil { return err } @@ -116,7 +116,7 @@ func ExecuteAtmosCmd() error { } if selectedCommand == "describe dependents" { - data, err := ExecuteDescribeDependents(cliConfig, selectedComponent, selectedStack, false) + data, err := ExecuteDescribeDependents(atmosConfig, selectedComponent, selectedStack, false) if err != nil { return err } @@ -128,7 +128,7 @@ func ExecuteAtmosCmd() error { } if selectedCommand == "validate component" { - _, err = ExecuteValidateComponent(cliConfig, schema.ConfigAndStacksInfo{}, selectedComponent, selectedStack, "", "", nil, 0) + _, err = ExecuteValidateComponent(atmosConfig, schema.ConfigAndStacksInfo{}, selectedComponent, selectedStack, "", "", nil, 0) if err != nil { return err } diff --git a/internal/exec/aws_eks_update_kubeconfig.go b/internal/exec/aws_eks_update_kubeconfig.go index 9380bacc7..eae912ac3 100644 --- a/internal/exec/aws_eks_update_kubeconfig.go +++ b/internal/exec/aws_eks_update_kubeconfig.go @@ -123,18 +123,18 @@ func ExecuteAwsEksUpdateKubeconfig(kubeconfigContext schema.AwsEksUpdateKubeconf shellCommandWorkingDir := "" var configAndStacksInfo schema.ConfigAndStacksInfo - var cliConfig schema.CliConfiguration + var atmosConfig schema.AtmosConfiguration var err error if !requiredParamsProvided { // If stack is not provided, calculate the stack name from the context (tenant, environment, stage) if kubeconfigContext.Stack == "" { - cliConfig, err = cfg.InitCliConfig(configAndStacksInfo, true) + atmosConfig, err = cfg.InitCliConfig(configAndStacksInfo, true) if err != nil { return err } - if len(GetStackNamePattern(cliConfig)) < 1 { + if len(GetStackNamePattern(atmosConfig)) < 1 { return errors.New("stack name pattern must be provided in 'stacks.name_pattern' CLI config or 'ATMOS_STACKS_NAME_PATTERN' ENV variable") } @@ -143,7 +143,7 @@ func ExecuteAwsEksUpdateKubeconfig(kubeconfigContext schema.AwsEksUpdateKubeconf kubeconfigContext.Tenant, kubeconfigContext.Environment, kubeconfigContext.Stage, - GetStackNamePattern(cliConfig), + GetStackNamePattern(atmosConfig), ) if err != nil { return err @@ -157,12 +157,12 @@ func ExecuteAwsEksUpdateKubeconfig(kubeconfigContext schema.AwsEksUpdateKubeconf configAndStacksInfo.Stack = kubeconfigContext.Stack configAndStacksInfo.ComponentType = "terraform" - configAndStacksInfo, err = ProcessStacks(cliConfig, configAndStacksInfo, true, true) - shellCommandWorkingDir = filepath.Join(cliConfig.TerraformDirAbsolutePath, configAndStacksInfo.ComponentFolderPrefix, configAndStacksInfo.FinalComponent) + configAndStacksInfo, err = ProcessStacks(atmosConfig, configAndStacksInfo, true, true) + shellCommandWorkingDir = filepath.Join(atmosConfig.TerraformDirAbsolutePath, configAndStacksInfo.ComponentFolderPrefix, configAndStacksInfo.FinalComponent) if err != nil { configAndStacksInfo.ComponentType = "helmfile" - configAndStacksInfo, err = ProcessStacks(cliConfig, configAndStacksInfo, true, true) - shellCommandWorkingDir = filepath.Join(cliConfig.HelmfileDirAbsolutePath, configAndStacksInfo.ComponentFolderPrefix, configAndStacksInfo.FinalComponent) + configAndStacksInfo, err = ProcessStacks(atmosConfig, configAndStacksInfo, true, true) + shellCommandWorkingDir = filepath.Join(atmosConfig.HelmfileDirAbsolutePath, configAndStacksInfo.ComponentFolderPrefix, configAndStacksInfo.FinalComponent) if err != nil { return err } @@ -175,16 +175,16 @@ func ExecuteAwsEksUpdateKubeconfig(kubeconfigContext schema.AwsEksUpdateKubeconf // `kubeconfig` can be overridden on the command line if kubeconfigPath == "" { - kubeconfigPath = fmt.Sprintf("%s/%s-kubecfg", cliConfig.Components.Helmfile.KubeconfigPath, kubeconfigContext.Stack) + kubeconfigPath = fmt.Sprintf("%s/%s-kubecfg", atmosConfig.Components.Helmfile.KubeconfigPath, kubeconfigContext.Stack) } // `clusterName` can be overridden on the command line if clusterName == "" { - clusterName = cfg.ReplaceContextTokens(context, cliConfig.Components.Helmfile.ClusterNamePattern) + clusterName = cfg.ReplaceContextTokens(context, atmosConfig.Components.Helmfile.ClusterNamePattern) } // `profile` can be overridden on the command line // `--role-arn` suppresses `profile` being automatically set if profile == "" && roleArn == "" { - profile = cfg.ReplaceContextTokens(context, cliConfig.Components.Helmfile.HelmAwsProfilePattern) + profile = cfg.ReplaceContextTokens(context, atmosConfig.Components.Helmfile.HelmAwsProfilePattern) } // `region` can be overridden on the command line if region == "" { @@ -224,14 +224,14 @@ func ExecuteAwsEksUpdateKubeconfig(kubeconfigContext schema.AwsEksUpdateKubeconf args = append(args, fmt.Sprintf("--region=%s", region)) } - err = ExecuteShellCommand(cliConfig, "aws", args, shellCommandWorkingDir, nil, dryRun, "") + err = ExecuteShellCommand(atmosConfig, "aws", args, shellCommandWorkingDir, nil, dryRun, "") if err != nil { return err } if kubeconfigPath != "" { message := fmt.Sprintf("\n'kubeconfig' has been downloaded to '%s'\nYou can set 'KUBECONFIG' ENV var to use in other scripts\n", kubeconfigPath) - u.LogDebug(cliConfig, message) + u.LogDebug(atmosConfig, message) } return nil diff --git a/internal/exec/describe_affected.go b/internal/exec/describe_affected.go index 645a9b0df..47ce0ed5a 100644 --- a/internal/exec/describe_affected.go +++ b/internal/exec/describe_affected.go @@ -16,7 +16,7 @@ import ( ) type DescribeAffectedCmdArgs struct { - CLIConfig schema.CliConfiguration + CLIConfig schema.AtmosConfiguration CloneTargetRef bool Format string IncludeDependents bool @@ -40,16 +40,16 @@ func parseDescribeAffectedCliArgs(cmd *cobra.Command, args []string) (DescribeAf return DescribeAffectedCmdArgs{}, err } - cliConfig, err := cfg.InitCliConfig(info, true) + atmosConfig, err := cfg.InitCliConfig(info, true) if err != nil { return DescribeAffectedCmdArgs{}, err } - logger, err := l.NewLoggerFromCliConfig(cliConfig) + logger, err := l.NewLoggerFromCliConfig(atmosConfig) if err != nil { return DescribeAffectedCmdArgs{}, err } - err = ValidateStacks(cliConfig) + err = ValidateStacks(atmosConfig) if err != nil { return DescribeAffectedCmdArgs{}, err } @@ -146,7 +146,7 @@ func parseDescribeAffectedCliArgs(cmd *cobra.Command, args []string) (DescribeAf } if verbose { - cliConfig.Logs.Level = u.LogLevelTrace + atmosConfig.Logs.Level = u.LogLevelTrace err := logger.SetLogLevel(l.LogLevelTrace) if err != nil { return DescribeAffectedCmdArgs{}, err @@ -154,7 +154,7 @@ func parseDescribeAffectedCliArgs(cmd *cobra.Command, args []string) (DescribeAf } result := DescribeAffectedCmdArgs{ - CLIConfig: cliConfig, + CLIConfig: atmosConfig, CloneTargetRef: cloneTargetRef, Format: format, IncludeDependents: includeDependents, diff --git a/internal/exec/describe_affected_utils.go b/internal/exec/describe_affected_utils.go index 9f41059f9..98c982604 100644 --- a/internal/exec/describe_affected_utils.go +++ b/internal/exec/describe_affected_utils.go @@ -32,7 +32,7 @@ var ( // ExecuteDescribeAffectedWithTargetRefClone clones the remote reference, // processes stack configs, and returns a list of the affected Atmos components and stacks given two Git commits func ExecuteDescribeAffectedWithTargetRefClone( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, ref string, sha string, sshKeyPath string, @@ -44,7 +44,7 @@ func ExecuteDescribeAffectedWithTargetRefClone( ) ([]schema.Affected, *plumbing.Reference, *plumbing.Reference, string, error) { if verbose { - cliConfig.Logs.Level = u.LogLevelTrace + atmosConfig.Logs.Level = u.LogLevelTrace } localRepo, err := g.GetLocalRepo() @@ -72,9 +72,9 @@ func ExecuteDescribeAffectedWithTargetRefClone( return nil, nil, nil, "", err } - defer removeTempDir(cliConfig, tempDir) + defer removeTempDir(atmosConfig, tempDir) - u.LogTrace(cliConfig, fmt.Sprintf("\nCloning repo '%s' into the temp dir '%s'", localRepoInfo.RepoUrl, tempDir)) + u.LogTrace(atmosConfig, fmt.Sprintf("\nCloning repo '%s' into the temp dir '%s'", localRepoInfo.RepoUrl, tempDir)) cloneOptions := git.CloneOptions{ URL: localRepoInfo.RepoUrl, @@ -85,9 +85,9 @@ func ExecuteDescribeAffectedWithTargetRefClone( // If `ref` flag is not provided, it will clone the HEAD of the default branch if ref != "" { cloneOptions.ReferenceName = plumbing.ReferenceName(ref) - u.LogTrace(cliConfig, fmt.Sprintf("\nCloning Git ref '%s' ...\n", ref)) + u.LogTrace(atmosConfig, fmt.Sprintf("\nCloning Git ref '%s' ...\n", ref)) } else { - u.LogTrace(cliConfig, "\nCloned the HEAD of the default branch ...\n") + u.LogTrace(atmosConfig, "\nCloned the HEAD of the default branch ...\n") } if verbose { @@ -127,14 +127,14 @@ func ExecuteDescribeAffectedWithTargetRefClone( } if ref != "" { - u.LogTrace(cliConfig, fmt.Sprintf("\nCloned Git ref '%s'\n", ref)) + u.LogTrace(atmosConfig, fmt.Sprintf("\nCloned Git ref '%s'\n", ref)) } else { - u.LogTrace(cliConfig, fmt.Sprintf("\nCloned Git ref '%s'\n", remoteRepoHead.Name())) + u.LogTrace(atmosConfig, fmt.Sprintf("\nCloned Git ref '%s'\n", remoteRepoHead.Name())) } // Check if a commit SHA was provided and checkout the repo at that commit SHA if sha != "" { - u.LogTrace(cliConfig, fmt.Sprintf("\nChecking out commit SHA '%s' ...\n", sha)) + u.LogTrace(atmosConfig, fmt.Sprintf("\nChecking out commit SHA '%s' ...\n", sha)) w, err := remoteRepo.Worktree() if err != nil { @@ -153,11 +153,11 @@ func ExecuteDescribeAffectedWithTargetRefClone( return nil, nil, nil, "", err } - u.LogTrace(cliConfig, fmt.Sprintf("\nChecked out commit SHA '%s'\n", sha)) + u.LogTrace(atmosConfig, fmt.Sprintf("\nChecked out commit SHA '%s'\n", sha)) } affected, localRepoHead, remoteRepoHead, err := executeDescribeAffected( - cliConfig, + atmosConfig, localRepoInfo.LocalWorktreePath, tempDir, localRepo, @@ -177,7 +177,7 @@ func ExecuteDescribeAffectedWithTargetRefClone( // ExecuteDescribeAffectedWithTargetRefCheckout checks out the target reference, // processes stack configs, and returns a list of the affected Atmos components and stacks given two Git commits func ExecuteDescribeAffectedWithTargetRefCheckout( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, ref string, sha string, verbose bool, @@ -187,7 +187,7 @@ func ExecuteDescribeAffectedWithTargetRefCheckout( ) ([]schema.Affected, *plumbing.Reference, *plumbing.Reference, string, error) { if verbose { - cliConfig.Logs.Level = u.LogLevelTrace + atmosConfig.Logs.Level = u.LogLevelTrace } localRepo, err := g.GetLocalRepo() @@ -206,10 +206,10 @@ func ExecuteDescribeAffectedWithTargetRefCheckout( return nil, nil, nil, "", err } - defer removeTempDir(cliConfig, tempDir) + defer removeTempDir(atmosConfig, tempDir) // Copy the local repo into the temp directory - u.LogTrace(cliConfig, fmt.Sprintf("\nCopying the local repo into the temp directory '%s' ...", tempDir)) + u.LogTrace(atmosConfig, fmt.Sprintf("\nCopying the local repo into the temp directory '%s' ...", tempDir)) copyOptions := cp.Options{ PreserveTimes: false, @@ -237,7 +237,7 @@ func ExecuteDescribeAffectedWithTargetRefCheckout( return nil, nil, nil, "", err } - u.LogTrace(cliConfig, fmt.Sprintf("Copied the local repo into the temp directory '%s'\n", tempDir)) + u.LogTrace(atmosConfig, fmt.Sprintf("Copied the local repo into the temp directory '%s'\n", tempDir)) remoteRepo, err := git.PlainOpenWithOptions(tempDir, &git.PlainOpenOptions{ DetectDotGit: false, @@ -254,7 +254,7 @@ func ExecuteDescribeAffectedWithTargetRefCheckout( } if sha != "" { - u.LogTrace(cliConfig, fmt.Sprintf("\nChecking out commit SHA '%s' ...\n", sha)) + u.LogTrace(atmosConfig, fmt.Sprintf("\nChecking out commit SHA '%s' ...\n", sha)) w, err := remoteRepo.Worktree() if err != nil { @@ -273,14 +273,14 @@ func ExecuteDescribeAffectedWithTargetRefCheckout( return nil, nil, nil, "", err } - u.LogTrace(cliConfig, fmt.Sprintf("Checked out commit SHA '%s'\n", sha)) + u.LogTrace(atmosConfig, fmt.Sprintf("Checked out commit SHA '%s'\n", sha)) } else { // If `ref` is not provided, use the HEAD of the remote origin if ref == "" { ref = "refs/remotes/origin/HEAD" } - u.LogTrace(cliConfig, fmt.Sprintf("\nChecking out Git ref '%s' ...", ref)) + u.LogTrace(atmosConfig, fmt.Sprintf("\nChecking out Git ref '%s' ...", ref)) w, err := remoteRepo.Worktree() if err != nil { @@ -305,11 +305,11 @@ func ExecuteDescribeAffectedWithTargetRefCheckout( return nil, nil, nil, "", err } - u.LogTrace(cliConfig, fmt.Sprintf("Checked out Git ref '%s'\n", ref)) + u.LogTrace(atmosConfig, fmt.Sprintf("Checked out Git ref '%s'\n", ref)) } affected, localRepoHead, remoteRepoHead, err := executeDescribeAffected( - cliConfig, + atmosConfig, localRepoInfo.LocalWorktreePath, tempDir, localRepo, @@ -329,7 +329,7 @@ func ExecuteDescribeAffectedWithTargetRefCheckout( // ExecuteDescribeAffectedWithTargetRepoPath uses `repo-path` to access the target repo, and processes stack configs // and returns a list of the affected Atmos components and stacks given two Git commits func ExecuteDescribeAffectedWithTargetRepoPath( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, targetRefPath string, verbose bool, includeSpaceliftAdminStacks bool, @@ -362,7 +362,7 @@ func ExecuteDescribeAffectedWithTargetRepoPath( } affected, localRepoHead, remoteRepoHead, err := executeDescribeAffected( - cliConfig, + atmosConfig, localRepoInfo.LocalWorktreePath, targetRefPath, localRepo, @@ -380,7 +380,7 @@ func ExecuteDescribeAffectedWithTargetRepoPath( } func executeDescribeAffected( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, localRepoFileSystemPath string, remoteRepoFileSystemPath string, localRepo *git.Repository, @@ -392,7 +392,7 @@ func executeDescribeAffected( ) ([]schema.Affected, *plumbing.Reference, *plumbing.Reference, error) { if verbose { - cliConfig.Logs.Level = u.LogLevelTrace + atmosConfig.Logs.Level = u.LogLevelTrace } localRepoHead, err := localRepo.Head() @@ -405,10 +405,10 @@ func executeDescribeAffected( return nil, nil, nil, err } - u.LogTrace(cliConfig, fmt.Sprintf("Current HEAD: %s", localRepoHead)) - u.LogTrace(cliConfig, fmt.Sprintf("BASE: %s", remoteRepoHead)) + u.LogTrace(atmosConfig, fmt.Sprintf("Current HEAD: %s", localRepoHead)) + u.LogTrace(atmosConfig, fmt.Sprintf("BASE: %s", remoteRepoHead)) - currentStacks, err := ExecuteDescribeStacks(cliConfig, stack, nil, nil, nil, false, true, false) + currentStacks, err := ExecuteDescribeStacks(atmosConfig, stack, nil, nil, nil, false, true, false) if err != nil { return nil, nil, nil, err } @@ -418,7 +418,7 @@ func executeDescribeAffected( return nil, nil, nil, err } - basePath := cliConfig.BasePath + basePath := atmosConfig.BasePath // Handle `atmos` absolute base path. // Absolute base path can be set in the `base_path` attribute in `atmos.yaml`, or using the ENV var `ATMOS_BASE_PATH` (as it's done in `geodesic`) @@ -432,56 +432,56 @@ func executeDescribeAffected( } // Update paths to point to the cloned remote repo dir - cliConfig.StacksBaseAbsolutePath = filepath.Join(remoteRepoFileSystemPath, basePath, cliConfig.Stacks.BasePath) - cliConfig.TerraformDirAbsolutePath = filepath.Join(remoteRepoFileSystemPath, basePath, cliConfig.Components.Terraform.BasePath) - cliConfig.HelmfileDirAbsolutePath = filepath.Join(remoteRepoFileSystemPath, basePath, cliConfig.Components.Helmfile.BasePath) + atmosConfig.StacksBaseAbsolutePath = filepath.Join(remoteRepoFileSystemPath, basePath, atmosConfig.Stacks.BasePath) + atmosConfig.TerraformDirAbsolutePath = filepath.Join(remoteRepoFileSystemPath, basePath, atmosConfig.Components.Terraform.BasePath) + atmosConfig.HelmfileDirAbsolutePath = filepath.Join(remoteRepoFileSystemPath, basePath, atmosConfig.Components.Helmfile.BasePath) - cliConfig.StackConfigFilesAbsolutePaths, err = u.JoinAbsolutePathWithPaths( - filepath.Join(remoteRepoFileSystemPath, basePath, cliConfig.Stacks.BasePath), - cliConfig.StackConfigFilesRelativePaths, + atmosConfig.StackConfigFilesAbsolutePaths, err = u.JoinAbsolutePathWithPaths( + filepath.Join(remoteRepoFileSystemPath, basePath, atmosConfig.Stacks.BasePath), + atmosConfig.StackConfigFilesRelativePaths, ) if err != nil { return nil, nil, nil, err } - remoteStacks, err := ExecuteDescribeStacks(cliConfig, stack, nil, nil, nil, true, true, false) + remoteStacks, err := ExecuteDescribeStacks(atmosConfig, stack, nil, nil, nil, true, true, false) if err != nil { return nil, nil, nil, err } - u.LogTrace(cliConfig, fmt.Sprintf("\nGetting current working repo commit object...")) + u.LogTrace(atmosConfig, fmt.Sprintf("\nGetting current working repo commit object...")) localCommit, err := localRepo.CommitObject(localRepoHead.Hash()) if err != nil { return nil, nil, nil, err } - u.LogTrace(cliConfig, fmt.Sprintf("Got current working repo commit object")) - u.LogTrace(cliConfig, fmt.Sprintf("Getting current working repo commit tree...")) + u.LogTrace(atmosConfig, fmt.Sprintf("Got current working repo commit object")) + u.LogTrace(atmosConfig, fmt.Sprintf("Getting current working repo commit tree...")) localTree, err := localCommit.Tree() if err != nil { return nil, nil, nil, err } - u.LogTrace(cliConfig, fmt.Sprintf("Got current working repo commit tree")) - u.LogTrace(cliConfig, fmt.Sprintf("Getting remote repo commit object...")) + u.LogTrace(atmosConfig, fmt.Sprintf("Got current working repo commit tree")) + u.LogTrace(atmosConfig, fmt.Sprintf("Getting remote repo commit object...")) remoteCommit, err := remoteRepo.CommitObject(remoteRepoHead.Hash()) if err != nil { return nil, nil, nil, err } - u.LogTrace(cliConfig, fmt.Sprintf("Got remote repo commit object")) - u.LogTrace(cliConfig, fmt.Sprintf("Getting remote repo commit tree...")) + u.LogTrace(atmosConfig, fmt.Sprintf("Got remote repo commit object")) + u.LogTrace(atmosConfig, fmt.Sprintf("Getting remote repo commit tree...")) remoteTree, err := remoteCommit.Tree() if err != nil { return nil, nil, nil, err } - u.LogTrace(cliConfig, fmt.Sprintf("Got remote repo commit tree")) - u.LogTrace(cliConfig, fmt.Sprintf("Finding difference between the current working branch and remote target branch ...")) + u.LogTrace(atmosConfig, fmt.Sprintf("Got remote repo commit tree")) + u.LogTrace(atmosConfig, fmt.Sprintf("Finding difference between the current working branch and remote target branch ...")) // Find a slice of Patch objects with all the changes between the current working and remote trees patch, err := localTree.Patch(remoteTree) @@ -492,22 +492,22 @@ func executeDescribeAffected( var changedFiles []string if len(patch.Stats()) > 0 { - u.LogTrace(cliConfig, fmt.Sprintf("Found difference between the current working branch and remote target branch")) - u.LogTrace(cliConfig, "\nChanged files:\n") + u.LogTrace(atmosConfig, fmt.Sprintf("Found difference between the current working branch and remote target branch")) + u.LogTrace(atmosConfig, "\nChanged files:\n") for _, fileStat := range patch.Stats() { - u.LogTrace(cliConfig, fileStat.Name) + u.LogTrace(atmosConfig, fileStat.Name) changedFiles = append(changedFiles, fileStat.Name) } - u.LogTrace(cliConfig, "") + u.LogTrace(atmosConfig, "") } else { - u.LogTrace(cliConfig, fmt.Sprintf("The current working branch and remote target branch are the same")) + u.LogTrace(atmosConfig, fmt.Sprintf("The current working branch and remote target branch are the same")) } affected, err := findAffected( currentStacks, remoteStacks, - cliConfig, + atmosConfig, changedFiles, includeSpaceliftAdminStacks, includeSettings, @@ -524,7 +524,7 @@ func executeDescribeAffected( func findAffected( currentStacks map[string]any, remoteStacks map[string]any, - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, changedFiles []string, includeSpaceliftAdminStacks bool, includeSettings bool, @@ -563,7 +563,7 @@ func findAffected( Affected: "stack.metadata", } res, err = appendToAffected( - cliConfig, + atmosConfig, componentName, stackName, componentSection, @@ -583,7 +583,7 @@ func findAffected( // Check the Terraform configuration of the component if component, ok := componentSection[cfg.ComponentSectionName].(string); ok && component != "" { // Check if the component uses some external modules (on the local filesystem) that have changed - changed, err := areTerraformComponentModulesChanged(component, cliConfig, changedFiles) + changed, err := areTerraformComponentModulesChanged(component, atmosConfig, changedFiles) if err != nil { return nil, err } @@ -596,7 +596,7 @@ func findAffected( Affected: "component.module", } res, err = appendToAffected( - cliConfig, + atmosConfig, componentName, stackName, componentSection, @@ -613,7 +613,7 @@ func findAffected( } // Check if any files in the component's folder have changed - changed, err = isComponentFolderChanged(component, "terraform", cliConfig, changedFiles) + changed, err = isComponentFolderChanged(component, "terraform", atmosConfig, changedFiles) if err != nil { return nil, err } @@ -626,7 +626,7 @@ func findAffected( Affected: "component", } res, err = appendToAffected( - cliConfig, + atmosConfig, componentName, stackName, componentSection, @@ -652,7 +652,7 @@ func findAffected( Affected: "stack.vars", } res, err = appendToAffected( - cliConfig, + atmosConfig, componentName, stackName, componentSection, @@ -678,7 +678,7 @@ func findAffected( Affected: "stack.env", } res, err = appendToAffected( - cliConfig, + atmosConfig, componentName, stackName, componentSection, @@ -704,7 +704,7 @@ func findAffected( Affected: "stack.settings", } res, err = appendToAffected( - cliConfig, + atmosConfig, componentName, stackName, componentSection, @@ -763,7 +763,7 @@ func findAffected( Folder: changedFolder, } res, err = appendToAffected( - cliConfig, + atmosConfig, componentName, stackName, componentSection, @@ -803,7 +803,7 @@ func findAffected( Affected: "stack.metadata", } res, err = appendToAffected( - cliConfig, + atmosConfig, componentName, stackName, componentSection, @@ -823,7 +823,7 @@ func findAffected( // Check the Helmfile configuration of the component if component, ok := componentSection[cfg.ComponentSectionName].(string); ok && component != "" { // Check if any files in the component's folder have changed - changed, err := isComponentFolderChanged(component, "helmfile", cliConfig, changedFiles) + changed, err := isComponentFolderChanged(component, "helmfile", atmosConfig, changedFiles) if err != nil { return nil, err } @@ -836,7 +836,7 @@ func findAffected( Affected: "component", } res, err = appendToAffected( - cliConfig, + atmosConfig, componentName, stackName, componentSection, @@ -862,7 +862,7 @@ func findAffected( Affected: "stack.vars", } res, err = appendToAffected( - cliConfig, + atmosConfig, componentName, stackName, componentSection, @@ -888,7 +888,7 @@ func findAffected( Affected: "stack.env", } res, err = appendToAffected( - cliConfig, + atmosConfig, componentName, stackName, componentSection, @@ -914,7 +914,7 @@ func findAffected( Affected: "stack.settings", } res, err = appendToAffected( - cliConfig, + atmosConfig, componentName, stackName, componentSection, @@ -973,7 +973,7 @@ func findAffected( Folder: changedFolder, } res, err = appendToAffected( - cliConfig, + atmosConfig, componentName, stackName, componentSection, @@ -1001,7 +1001,7 @@ func findAffected( // appendToAffected adds an item to the affected list, and adds the Spacelift stack and Atlantis project (if configured) func appendToAffected( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, componentName string, stackName string, componentSection map[string]any, @@ -1048,14 +1048,14 @@ func appendToAffected( } // Affected Spacelift stack - spaceliftStackName, err := BuildSpaceliftStackNameFromComponentConfig(cliConfig, configAndStacksInfo) + spaceliftStackName, err := BuildSpaceliftStackNameFromComponentConfig(atmosConfig, configAndStacksInfo) if err != nil { return nil, err } affected.SpaceliftStack = spaceliftStackName // Affected Atlantis project - atlantisProjectName, err := BuildAtlantisProjectNameFromComponentConfig(cliConfig, configAndStacksInfo) + atlantisProjectName, err := BuildAtlantisProjectNameFromComponentConfig(atmosConfig, configAndStacksInfo) if err != nil { return nil, err } @@ -1063,7 +1063,7 @@ func appendToAffected( if includeSpaceliftAdminStacks { affectedList, err = addAffectedSpaceliftAdminStack( - cliConfig, + atmosConfig, affectedList, settingsSection, stacks, @@ -1079,7 +1079,7 @@ func appendToAffected( } // Check `component` section and add `ComponentPath` to the output - affected.ComponentPath = BuildComponentPath(cliConfig, componentSection, affected.ComponentType) + affected.ComponentPath = BuildComponentPath(atmosConfig, componentSection, affected.ComponentType) affected.StackSlug = fmt.Sprintf("%s-%s", stackName, strings.Replace(componentName, "/", "-", -1)) return append(affectedList, affected), nil @@ -1174,7 +1174,7 @@ func isComponentDependentFolderOrFileChanged( func isComponentFolderChanged( component string, componentType string, - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, changedFiles []string, ) (bool, error) { @@ -1182,9 +1182,9 @@ func isComponentFolderChanged( switch componentType { case "terraform": - componentPath = filepath.Join(cliConfig.BasePath, cliConfig.Components.Terraform.BasePath, component) + componentPath = filepath.Join(atmosConfig.BasePath, atmosConfig.Components.Terraform.BasePath, component) case "helmfile": - componentPath = filepath.Join(cliConfig.BasePath, cliConfig.Components.Helmfile.BasePath, component) + componentPath = filepath.Join(atmosConfig.BasePath, atmosConfig.Components.Helmfile.BasePath, component) } componentPathAbs, err := filepath.Abs(componentPath) @@ -1216,11 +1216,11 @@ func isComponentFolderChanged( // areTerraformComponentModulesChanged checks if any of the external Terraform modules (but on the local filesystem) that the component uses have changed func areTerraformComponentModulesChanged( component string, - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, changedFiles []string, ) (bool, error) { - componentPath := filepath.Join(cliConfig.BasePath, cliConfig.Components.Terraform.BasePath, component) + componentPath := filepath.Join(atmosConfig.BasePath, atmosConfig.Components.Terraform.BasePath, component) componentPathAbs, err := filepath.Abs(componentPath) if err != nil { @@ -1266,7 +1266,7 @@ func areTerraformComponentModulesChanged( // addAffectedSpaceliftAdminStack adds the affected Spacelift admin stack that manages the affected child stack func addAffectedSpaceliftAdminStack( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, affectedList []schema.Affected, settingsSection map[string]any, stacks map[string]any, @@ -1310,13 +1310,13 @@ func addAffectedSpaceliftAdminStack( var adminStackContextPrefix string - if cliConfig.Stacks.NameTemplate != "" { - adminStackContextPrefix, err = ProcessTmpl("spacelift-admin-stack-name-template", cliConfig.Stacks.NameTemplate, configAndStacksInfo.ComponentSection, false) + if atmosConfig.Stacks.NameTemplate != "" { + adminStackContextPrefix, err = ProcessTmpl("spacelift-admin-stack-name-template", atmosConfig.Stacks.NameTemplate, configAndStacksInfo.ComponentSection, false) if err != nil { return nil, err } } else { - adminStackContextPrefix, err = cfg.GetContextPrefix(currentStackName, adminStackContext, GetStackNamePattern(cliConfig), currentStackName) + adminStackContextPrefix, err = cfg.GetContextPrefix(currentStackName, adminStackContext, GetStackNamePattern(atmosConfig), currentStackName) if err != nil { return nil, err } @@ -1346,13 +1346,13 @@ func addAffectedSpaceliftAdminStack( var contextPrefix string - if cliConfig.Stacks.NameTemplate != "" { - contextPrefix, err = ProcessTmpl("spacelift-stack-name-template", cliConfig.Stacks.NameTemplate, configAndStacksInfo.ComponentSection, false) + if atmosConfig.Stacks.NameTemplate != "" { + contextPrefix, err = ProcessTmpl("spacelift-stack-name-template", atmosConfig.Stacks.NameTemplate, configAndStacksInfo.ComponentSection, false) if err != nil { return nil, err } } else { - contextPrefix, err = cfg.GetContextPrefix(stackName, context, GetStackNamePattern(cliConfig), stackName) + contextPrefix, err = cfg.GetContextPrefix(stackName, context, GetStackNamePattern(atmosConfig), stackName) if err != nil { return nil, err } @@ -1389,7 +1389,7 @@ func addAffectedSpaceliftAdminStack( } affectedList, err = appendToAffected( - cliConfig, + atmosConfig, componentName, stackName, componentSection, @@ -1415,21 +1415,21 @@ func addAffectedSpaceliftAdminStack( // addDependentsToAffected adds dependent components and stacks to each affected component func addDependentsToAffected( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, affected *[]schema.Affected, includeSettings bool, ) error { for i := 0; i < len(*affected); i++ { a := &(*affected)[i] - deps, err := ExecuteDescribeDependents(cliConfig, a.Component, a.Stack, includeSettings) + deps, err := ExecuteDescribeDependents(atmosConfig, a.Component, a.Stack, includeSettings) if err != nil { return err } if len(deps) > 0 { a.Dependents = deps - err = addDependentsToDependents(cliConfig, &deps, includeSettings) + err = addDependentsToDependents(atmosConfig, &deps, includeSettings) if err != nil { return err } @@ -1444,21 +1444,21 @@ func addDependentsToAffected( // addDependentsToDependents recursively adds dependent components and stacks to each dependent component func addDependentsToDependents( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, dependents *[]schema.Dependent, includeSettings bool, ) error { for i := 0; i < len(*dependents); i++ { d := &(*dependents)[i] - deps, err := ExecuteDescribeDependents(cliConfig, d.Component, d.Stack, includeSettings) + deps, err := ExecuteDescribeDependents(atmosConfig, d.Component, d.Stack, includeSettings) if err != nil { return err } if len(deps) > 0 { d.Dependents = deps - err = addDependentsToDependents(cliConfig, &deps, includeSettings) + err = addDependentsToDependents(atmosConfig, &deps, includeSettings) if err != nil { return err } diff --git a/internal/exec/describe_component.go b/internal/exec/describe_component.go index 5afea0dd7..099564b74 100644 --- a/internal/exec/describe_component.go +++ b/internal/exec/describe_component.go @@ -67,16 +67,16 @@ func ExecuteDescribeComponent( configAndStacksInfo.ComponentFromArg = component configAndStacksInfo.Stack = stack - cliConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) + atmosConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) if err != nil { return nil, err } configAndStacksInfo.ComponentType = "terraform" - configAndStacksInfo, err = ProcessStacks(cliConfig, configAndStacksInfo, true, processTemplates) + configAndStacksInfo, err = ProcessStacks(atmosConfig, configAndStacksInfo, true, processTemplates) if err != nil { configAndStacksInfo.ComponentType = "helmfile" - configAndStacksInfo, err = ProcessStacks(cliConfig, configAndStacksInfo, true, processTemplates) + configAndStacksInfo, err = ProcessStacks(atmosConfig, configAndStacksInfo, true, processTemplates) if err != nil { return nil, err } diff --git a/internal/exec/describe_config.go b/internal/exec/describe_config.go index 16ed84075..0c39ba490 100644 --- a/internal/exec/describe_config.go +++ b/internal/exec/describe_config.go @@ -20,12 +20,12 @@ func ExecuteDescribeConfigCmd(cmd *cobra.Command, args []string) error { return err } - cliConfig, err := cfg.InitCliConfig(info, false) + atmosConfig, err := cfg.InitCliConfig(info, false) if err != nil { return err } - err = printOrWriteToFile(format, "", cliConfig) + err = printOrWriteToFile(format, "", atmosConfig) if err != nil { return err } diff --git a/internal/exec/describe_dependents.go b/internal/exec/describe_dependents.go index c69663014..65f74e346 100644 --- a/internal/exec/describe_dependents.go +++ b/internal/exec/describe_dependents.go @@ -20,12 +20,12 @@ func ExecuteDescribeDependentsCmd(cmd *cobra.Command, args []string) error { return err } - cliConfig, err := cfg.InitCliConfig(info, true) + atmosConfig, err := cfg.InitCliConfig(info, true) if err != nil { return err } - err = ValidateStacks(cliConfig) + err = ValidateStacks(atmosConfig) if err != nil { return err } @@ -53,7 +53,7 @@ func ExecuteDescribeDependentsCmd(cmd *cobra.Command, args []string) error { component := args[0] - dependents, err := ExecuteDescribeDependents(cliConfig, component, stack, false) + dependents, err := ExecuteDescribeDependents(atmosConfig, component, stack, false) if err != nil { return err } @@ -68,7 +68,7 @@ func ExecuteDescribeDependentsCmd(cmd *cobra.Command, args []string) error { // ExecuteDescribeDependents produces a list of Atmos components in Atmos stacks that depend on the provided Atmos component func ExecuteDescribeDependents( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, component string, stack string, includeSettings bool, @@ -78,7 +78,7 @@ func ExecuteDescribeDependents( var ok bool // Get all stacks with all components - stacks, err := ExecuteDescribeStacks(cliConfig, "", nil, nil, nil, false, true, false) + stacks, err := ExecuteDescribeStacks(atmosConfig, "", nil, nil, nil, false, true, false) if err != nil { return nil, err } @@ -224,7 +224,7 @@ func ExecuteDescribeDependents( dependent := schema.Dependent{ Component: stackComponentName, - ComponentPath: BuildComponentPath(cliConfig, stackComponentMap, stackComponentType), + ComponentPath: BuildComponentPath(atmosConfig, stackComponentMap, stackComponentType), ComponentType: stackComponentType, Stack: stackName, StackSlug: fmt.Sprintf("%s-%s", stackName, strings.Replace(stackComponentName, "/", "-", -1)), @@ -248,14 +248,14 @@ func ExecuteDescribeDependents( }, } - spaceliftStackName, err := BuildSpaceliftStackNameFromComponentConfig(cliConfig, configAndStacksInfo) + spaceliftStackName, err := BuildSpaceliftStackNameFromComponentConfig(atmosConfig, configAndStacksInfo) if err != nil { return nil, err } dependent.SpaceliftStack = spaceliftStackName // Atlantis project - atlantisProjectName, err := BuildAtlantisProjectNameFromComponentConfig(cliConfig, configAndStacksInfo) + atlantisProjectName, err := BuildAtlantisProjectNameFromComponentConfig(atmosConfig, configAndStacksInfo) if err != nil { return nil, err } diff --git a/internal/exec/describe_stacks.go b/internal/exec/describe_stacks.go index 9e4fb7b6a..96bae5444 100644 --- a/internal/exec/describe_stacks.go +++ b/internal/exec/describe_stacks.go @@ -20,12 +20,12 @@ func ExecuteDescribeStacksCmd(cmd *cobra.Command, args []string) error { return err } - cliConfig, err := cfg.InitCliConfig(info, true) + atmosConfig, err := cfg.InitCliConfig(info, true) if err != nil { return err } - err = ValidateStacks(cliConfig) + err = ValidateStacks(atmosConfig) if err != nil { return err } @@ -95,7 +95,7 @@ func ExecuteDescribeStacksCmd(cmd *cobra.Command, args []string) error { } finalStacksMap, err := ExecuteDescribeStacks( - cliConfig, + atmosConfig, filterByStack, components, componentTypes, @@ -118,7 +118,7 @@ func ExecuteDescribeStacksCmd(cmd *cobra.Command, args []string) error { // ExecuteDescribeStacks processes stack manifests and returns the final map of stacks and components func ExecuteDescribeStacks( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, filterByStack string, components []string, componentTypes []string, @@ -128,7 +128,7 @@ func ExecuteDescribeStacks( includeEmptyStacks bool, ) (map[string]any, error) { - stacksMap, _, err := FindStacksMap(cliConfig, ignoreMissingFiles) + stacksMap, _, err := FindStacksMap(atmosConfig, ignoreMissingFiles) if err != nil { return nil, err } @@ -266,15 +266,15 @@ func ExecuteDescribeStacks( } // Stack name - if cliConfig.Stacks.NameTemplate != "" { - stackName, err = ProcessTmpl("describe-stacks-name-template", cliConfig.Stacks.NameTemplate, configAndStacksInfo.ComponentSection, false) + if atmosConfig.Stacks.NameTemplate != "" { + stackName, err = ProcessTmpl("describe-stacks-name-template", atmosConfig.Stacks.NameTemplate, configAndStacksInfo.ComponentSection, false) if err != nil { return nil, err } } else { context = cfg.GetContextFromVars(varsSection) configAndStacksInfo.Context = context - stackName, err = cfg.GetContextPrefix(stackFileName, context, GetStackNamePattern(cliConfig), stackFileName) + stackName, err = cfg.GetContextPrefix(stackFileName, context, GetStackNamePattern(atmosConfig), stackFileName) if err != nil { return nil, err } @@ -318,7 +318,7 @@ func ExecuteDescribeStacks( componentSection["atmos_manifest"] = stackFileName // Terraform workspace - workspace, err := BuildTerraformWorkspace(cliConfig, configAndStacksInfo) + workspace, err := BuildTerraformWorkspace(atmosConfig, configAndStacksInfo) if err != nil { return nil, err } @@ -339,7 +339,7 @@ func ExecuteDescribeStacks( } componentSectionProcessed, err := ProcessTmplWithDatasources( - cliConfig, + atmosConfig, settingsSectionStruct, "describe-stacks-all-sections", componentSectionStr, @@ -352,17 +352,17 @@ func ExecuteDescribeStacks( componentSectionConverted, err := u.UnmarshalYAML[schema.AtmosSectionMapType](componentSectionProcessed) if err != nil { - if !cliConfig.Templates.Settings.Enabled { + if !atmosConfig.Templates.Settings.Enabled { if strings.Contains(componentSectionStr, "{{") || strings.Contains(componentSectionStr, "}}") { errorMessage := "the stack manifests contain Go templates, but templating is disabled in atmos.yaml in 'templates.settings.enabled'\n" + "to enable templating, refer to https://atmos.tools/core-concepts/stacks/templates" err = errors.Join(err, errors.New(errorMessage)) } } - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } - componentSectionFinal, err := ProcessCustomYamlTags(cliConfig, componentSectionConverted, stackName) + componentSectionFinal, err := ProcessCustomYamlTags(atmosConfig, componentSectionConverted, stackName) if err != nil { return nil, err } @@ -459,15 +459,15 @@ func ExecuteDescribeStacks( } // Stack name - if cliConfig.Stacks.NameTemplate != "" { - stackName, err = ProcessTmpl("describe-stacks-name-template", cliConfig.Stacks.NameTemplate, configAndStacksInfo.ComponentSection, false) + if atmosConfig.Stacks.NameTemplate != "" { + stackName, err = ProcessTmpl("describe-stacks-name-template", atmosConfig.Stacks.NameTemplate, configAndStacksInfo.ComponentSection, false) if err != nil { return nil, err } } else { context = cfg.GetContextFromVars(varsSection) configAndStacksInfo.Context = context - stackName, err = cfg.GetContextPrefix(stackFileName, context, GetStackNamePattern(cliConfig), stackFileName) + stackName, err = cfg.GetContextPrefix(stackFileName, context, GetStackNamePattern(atmosConfig), stackFileName) if err != nil { return nil, err } @@ -524,7 +524,7 @@ func ExecuteDescribeStacks( } componentSectionProcessed, err := ProcessTmplWithDatasources( - cliConfig, + atmosConfig, settingsSectionStruct, "describe-stacks-all-sections", componentSectionStr, @@ -537,17 +537,17 @@ func ExecuteDescribeStacks( componentSectionConverted, err := u.UnmarshalYAML[schema.AtmosSectionMapType](componentSectionProcessed) if err != nil { - if !cliConfig.Templates.Settings.Enabled { + if !atmosConfig.Templates.Settings.Enabled { if strings.Contains(componentSectionStr, "{{") || strings.Contains(componentSectionStr, "}}") { errorMessage := "the stack manifests contain Go templates, but templating is disabled in atmos.yaml in 'templates.settings.enabled'\n" + "to enable templating, refer to https://atmos.tools/core-concepts/stacks/templates" err = errors.Join(err, errors.New(errorMessage)) } } - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } - componentSectionFinal, err := ProcessCustomYamlTags(cliConfig, componentSectionConverted, stackName) + componentSectionFinal, err := ProcessCustomYamlTags(atmosConfig, componentSectionConverted, stackName) if err != nil { return nil, err } diff --git a/internal/exec/describe_workflows.go b/internal/exec/describe_workflows.go index af71b9046..0b93153f8 100644 --- a/internal/exec/describe_workflows.go +++ b/internal/exec/describe_workflows.go @@ -14,7 +14,7 @@ func ExecuteDescribeWorkflowsCmd(cmd *cobra.Command, args []string) error { return err } - cliConfig, err := cfg.InitCliConfig(info, true) + atmosConfig, err := cfg.InitCliConfig(info, true) if err != nil { return err } @@ -47,7 +47,7 @@ func ExecuteDescribeWorkflowsCmd(cmd *cobra.Command, args []string) error { outputType = "list" } - describeWorkflowsList, describeWorkflowsMap, describeWorkflowsAll, err := ExecuteDescribeWorkflows(cliConfig) + describeWorkflowsList, describeWorkflowsMap, describeWorkflowsAll, err := ExecuteDescribeWorkflows(atmosConfig) if err != nil { return err } diff --git a/internal/exec/file_utils.go b/internal/exec/file_utils.go index bd5dc7d28..4d65f8610 100644 --- a/internal/exec/file_utils.go +++ b/internal/exec/file_utils.go @@ -9,17 +9,17 @@ import ( u "github.com/cloudposse/atmos/pkg/utils" ) -func removeTempDir(cliConfig schema.CliConfiguration, path string) { +func removeTempDir(atmosConfig schema.AtmosConfiguration, path string) { err := os.RemoveAll(path) if err != nil { - u.LogWarning(cliConfig, err.Error()) + u.LogWarning(atmosConfig, err.Error()) } } func closeFile(fileName string, file io.ReadCloser) { err := file.Close() if err != nil { - u.LogError(schema.CliConfiguration{}, fmt.Errorf("error closing the file '%s': %v", fileName, err)) + u.LogError(schema.AtmosConfiguration{}, fmt.Errorf("error closing the file '%s': %v", fileName, err)) } } diff --git a/internal/exec/helmfile.go b/internal/exec/helmfile.go index bb127902d..5aeb56361 100644 --- a/internal/exec/helmfile.go +++ b/internal/exec/helmfile.go @@ -28,7 +28,7 @@ func ExecuteHelmfileCmd(cmd *cobra.Command, args []string, additionalArgsAndFlag // ExecuteHelmfile executes helmfile commands func ExecuteHelmfile(info schema.ConfigAndStacksInfo) error { - cliConfig, err := cfg.InitCliConfig(info, true) + atmosConfig, err := cfg.InitCliConfig(info, true) if err != nil { return err } @@ -45,7 +45,7 @@ func ExecuteHelmfile(info schema.ConfigAndStacksInfo) error { return err } - err = processHelp(cliConfig, "helmfile", "") + err = processHelp(atmosConfig, "helmfile", "") if err != nil { return err } @@ -55,10 +55,10 @@ func ExecuteHelmfile(info schema.ConfigAndStacksInfo) error { } if info.SubCommand == "version" { - return ExecuteShellCommand(cliConfig, "helmfile", []string{info.SubCommand}, "", nil, false, info.RedirectStdErr) + return ExecuteShellCommand(atmosConfig, "helmfile", []string{info.SubCommand}, "", nil, false, info.RedirectStdErr) } - info, err = ProcessStacks(cliConfig, info, true, true) + info, err = ProcessStacks(atmosConfig, info, true, true) if err != nil { return err } @@ -68,23 +68,23 @@ func ExecuteHelmfile(info schema.ConfigAndStacksInfo) error { } if !info.ComponentIsEnabled { - u.LogInfo(cliConfig, fmt.Sprintf("component '%s' is not enabled and skipped", info.ComponentFromArg)) + u.LogInfo(atmosConfig, fmt.Sprintf("component '%s' is not enabled and skipped", info.ComponentFromArg)) return nil } - err = checkHelmfileConfig(cliConfig) + err = checkHelmfileConfig(atmosConfig) if err != nil { return err } // Check if the component exists as a helmfile component - componentPath := filepath.Join(cliConfig.HelmfileDirAbsolutePath, info.ComponentFolderPrefix, info.FinalComponent) + componentPath := filepath.Join(atmosConfig.HelmfileDirAbsolutePath, info.ComponentFolderPrefix, info.FinalComponent) componentPathExists, err := u.IsDirectory(componentPath) if err != nil || !componentPathExists { return fmt.Errorf("'%s' points to the Helmfile component '%s', but it does not exist in '%s'", info.ComponentFromArg, info.FinalComponent, - filepath.Join(cliConfig.Components.Helmfile.BasePath, info.ComponentFolderPrefix), + filepath.Join(atmosConfig.Components.Helmfile.BasePath, info.ComponentFolderPrefix), ) } @@ -95,17 +95,17 @@ func ExecuteHelmfile(info schema.ConfigAndStacksInfo) error { } // Print component variables - u.LogDebug(cliConfig, fmt.Sprintf("\nVariables for the component '%s' in the stack '%s':", info.ComponentFromArg, info.Stack)) + u.LogDebug(atmosConfig, fmt.Sprintf("\nVariables for the component '%s' in the stack '%s':", info.ComponentFromArg, info.Stack)) - if cliConfig.Logs.Level == u.LogLevelTrace || cliConfig.Logs.Level == u.LogLevelDebug { - err = u.PrintAsYAMLToFileDescriptor(cliConfig, info.ComponentVarsSection) + if atmosConfig.Logs.Level == u.LogLevelTrace || atmosConfig.Logs.Level == u.LogLevelDebug { + err = u.PrintAsYAMLToFileDescriptor(atmosConfig, info.ComponentVarsSection) if err != nil { return err } } // Check if component 'settings.validation' section is specified and validate the component - valid, err := ValidateComponent(cliConfig, info.ComponentFromArg, info.ComponentSection, "", "", nil, 0) + valid, err := ValidateComponent(atmosConfig, info.ComponentFromArg, info.ComponentSection, "", "", nil, 0) if err != nil { return err } @@ -115,10 +115,10 @@ func ExecuteHelmfile(info schema.ConfigAndStacksInfo) error { // Write variables to a file varFile := constructHelmfileComponentVarfileName(info) - varFilePath := constructHelmfileComponentVarfilePath(cliConfig, info) + varFilePath := constructHelmfileComponentVarfilePath(atmosConfig, info) - u.LogDebug(cliConfig, "Writing the variables to file:") - u.LogDebug(cliConfig, varFilePath) + u.LogDebug(atmosConfig, "Writing the variables to file:") + u.LogDebug(atmosConfig, varFilePath) if !info.DryRun { err = u.WriteToFileAsYAML(varFilePath, info.ComponentVarsSection, 0644) @@ -136,18 +136,18 @@ func ExecuteHelmfile(info schema.ConfigAndStacksInfo) error { envVarsEKS := []string{} - if cliConfig.Components.Helmfile.UseEKS { + if atmosConfig.Components.Helmfile.UseEKS { // Prepare AWS profile - helmAwsProfile := cfg.ReplaceContextTokens(context, cliConfig.Components.Helmfile.HelmAwsProfilePattern) - u.LogDebug(cliConfig, fmt.Sprintf("\nUsing AWS_PROFILE=%s\n\n", helmAwsProfile)) + helmAwsProfile := cfg.ReplaceContextTokens(context, atmosConfig.Components.Helmfile.HelmAwsProfilePattern) + u.LogDebug(atmosConfig, fmt.Sprintf("\nUsing AWS_PROFILE=%s\n\n", helmAwsProfile)) // Download kubeconfig by running `aws eks update-kubeconfig` - kubeconfigPath := fmt.Sprintf("%s/%s-kubecfg", cliConfig.Components.Helmfile.KubeconfigPath, info.ContextPrefix) - clusterName := cfg.ReplaceContextTokens(context, cliConfig.Components.Helmfile.ClusterNamePattern) - u.LogDebug(cliConfig, fmt.Sprintf("Downloading kubeconfig from the cluster '%s' and saving it to %s\n\n", clusterName, kubeconfigPath)) + kubeconfigPath := fmt.Sprintf("%s/%s-kubecfg", atmosConfig.Components.Helmfile.KubeconfigPath, info.ContextPrefix) + clusterName := cfg.ReplaceContextTokens(context, atmosConfig.Components.Helmfile.ClusterNamePattern) + u.LogDebug(atmosConfig, fmt.Sprintf("Downloading kubeconfig from the cluster '%s' and saving it to %s\n\n", clusterName, kubeconfigPath)) err = ExecuteShellCommand( - cliConfig, + atmosConfig, "aws", []string{ "--profile", @@ -174,33 +174,33 @@ func ExecuteHelmfile(info schema.ConfigAndStacksInfo) error { } // Print command info - u.LogDebug(cliConfig, "\nCommand info:") - u.LogDebug(cliConfig, "Helmfile binary: "+info.Command) - u.LogDebug(cliConfig, "Helmfile command: "+info.SubCommand) + u.LogDebug(atmosConfig, "\nCommand info:") + u.LogDebug(atmosConfig, "Helmfile binary: "+info.Command) + u.LogDebug(atmosConfig, "Helmfile command: "+info.SubCommand) // https://github.com/roboll/helmfile#cli-reference // atmos helmfile diff echo-server -s tenant1-ue2-dev --global-options "--no-color --namespace=test" // atmos helmfile diff echo-server -s tenant1-ue2-dev --global-options "--no-color --namespace test" // atmos helmfile diff echo-server -s tenant1-ue2-dev --global-options="--no-color --namespace=test" // atmos helmfile diff echo-server -s tenant1-ue2-dev --global-options="--no-color --namespace test" - u.LogDebug(cliConfig, fmt.Sprintf("Global options: %v", info.GlobalOptions)) + u.LogDebug(atmosConfig, fmt.Sprintf("Global options: %v", info.GlobalOptions)) - u.LogDebug(cliConfig, fmt.Sprintf("Arguments and flags: %v", info.AdditionalArgsAndFlags)) - u.LogDebug(cliConfig, "Component: "+info.ComponentFromArg) + u.LogDebug(atmosConfig, fmt.Sprintf("Arguments and flags: %v", info.AdditionalArgsAndFlags)) + u.LogDebug(atmosConfig, "Component: "+info.ComponentFromArg) if len(info.BaseComponent) > 0 { - u.LogDebug(cliConfig, "Helmfile component: "+info.BaseComponent) + u.LogDebug(atmosConfig, "Helmfile component: "+info.BaseComponent) } if info.Stack == info.StackFromArg { - u.LogDebug(cliConfig, "Stack: "+info.StackFromArg) + u.LogDebug(atmosConfig, "Stack: "+info.StackFromArg) } else { - u.LogDebug(cliConfig, "Stack: "+info.StackFromArg) - u.LogDebug(cliConfig, "Stack path: "+filepath.Join(cliConfig.BasePath, cliConfig.Stacks.BasePath, info.Stack)) + u.LogDebug(atmosConfig, "Stack: "+info.StackFromArg) + u.LogDebug(atmosConfig, "Stack path: "+filepath.Join(atmosConfig.BasePath, atmosConfig.Stacks.BasePath, info.Stack)) } - workingDir := constructHelmfileComponentWorkingDir(cliConfig, info) - u.LogDebug(cliConfig, fmt.Sprintf("Working dir: %s\n\n", workingDir)) + workingDir := constructHelmfileComponentWorkingDir(atmosConfig, info) + u.LogDebug(atmosConfig, fmt.Sprintf("Working dir: %s\n\n", workingDir)) // Prepare arguments and flags allArgsAndFlags := []string{"--state-values-file", varFile} @@ -237,21 +237,21 @@ func ExecuteHelmfile(info schema.ConfigAndStacksInfo) error { envVars = append(envVars, fmt.Sprintf("REGION=%s", context.Region)) } - if cliConfig.Components.Helmfile.KubeconfigPath != "" { - envVars = append(envVars, fmt.Sprintf("KUBECONFIG=%s", cliConfig.Components.Helmfile.KubeconfigPath)) + if atmosConfig.Components.Helmfile.KubeconfigPath != "" { + envVars = append(envVars, fmt.Sprintf("KUBECONFIG=%s", atmosConfig.Components.Helmfile.KubeconfigPath)) } - if cliConfig.Components.Helmfile.UseEKS { + if atmosConfig.Components.Helmfile.UseEKS { envVars = append(envVars, envVarsEKS...) } - u.LogTrace(cliConfig, "Using ENV vars:") + u.LogTrace(atmosConfig, "Using ENV vars:") for _, v := range envVars { - u.LogTrace(cliConfig, v) + u.LogTrace(atmosConfig, v) } err = ExecuteShellCommand( - cliConfig, + atmosConfig, info.Command, allArgsAndFlags, componentPath, @@ -266,30 +266,30 @@ func ExecuteHelmfile(info schema.ConfigAndStacksInfo) error { // Cleanup err = os.Remove(varFilePath) if err != nil { - u.LogWarning(cliConfig, err.Error()) + u.LogWarning(atmosConfig, err.Error()) } return nil } -func checkHelmfileConfig(cliConfig schema.CliConfiguration) error { - if len(cliConfig.Components.Helmfile.BasePath) < 1 { +func checkHelmfileConfig(atmosConfig schema.AtmosConfiguration) error { + if len(atmosConfig.Components.Helmfile.BasePath) < 1 { return errors.New("Base path to helmfile components must be provided in 'components.helmfile.base_path' config or " + "'ATMOS_COMPONENTS_HELMFILE_BASE_PATH' ENV variable") } - if cliConfig.Components.Helmfile.UseEKS { - if len(cliConfig.Components.Helmfile.KubeconfigPath) < 1 { + if atmosConfig.Components.Helmfile.UseEKS { + if len(atmosConfig.Components.Helmfile.KubeconfigPath) < 1 { return errors.New("Kubeconfig path must be provided in 'components.helmfile.kubeconfig_path' config or " + "'ATMOS_COMPONENTS_HELMFILE_KUBECONFIG_PATH' ENV variable") } - if len(cliConfig.Components.Helmfile.HelmAwsProfilePattern) < 1 { + if len(atmosConfig.Components.Helmfile.HelmAwsProfilePattern) < 1 { return errors.New("Helm AWS profile pattern must be provided in 'components.helmfile.helm_aws_profile_pattern' config or " + "'ATMOS_COMPONENTS_HELMFILE_HELM_AWS_PROFILE_PATTERN' ENV variable") } - if len(cliConfig.Components.Helmfile.ClusterNamePattern) < 1 { + if len(atmosConfig.Components.Helmfile.ClusterNamePattern) < 1 { return errors.New("Cluster name pattern must be provided in 'components.helmfile.cluster_name_pattern' config or " + "'ATMOS_COMPONENTS_HELMFILE_CLUSTER_NAME_PATTERN' ENV variable") } diff --git a/internal/exec/helmfile_generate_varfile.go b/internal/exec/helmfile_generate_varfile.go index 9a98e0944..2f1ac4da8 100644 --- a/internal/exec/helmfile_generate_varfile.go +++ b/internal/exec/helmfile_generate_varfile.go @@ -34,12 +34,12 @@ func ExecuteHelmfileGenerateVarfileCmd(cmd *cobra.Command, args []string) error info.Stack = stack info.ComponentType = "helmfile" - cliConfig, err := cfg.InitCliConfig(info, true) + atmosConfig, err := cfg.InitCliConfig(info, true) if err != nil { return err } - info, err = ProcessStacks(cliConfig, info, true, true) + info, err = ProcessStacks(atmosConfig, info, true, true) if err != nil { return err } @@ -55,22 +55,22 @@ func ExecuteHelmfileGenerateVarfileCmd(cmd *cobra.Command, args []string) error if len(varFileNameFromArg) > 0 { varFilePath = varFileNameFromArg } else { - varFilePath = constructHelmfileComponentVarfilePath(cliConfig, info) + varFilePath = constructHelmfileComponentVarfilePath(atmosConfig, info) } // Print the component variables - u.LogDebug(cliConfig, fmt.Sprintf("\nVariables for the component '%s' in the stack '%s':", info.ComponentFromArg, info.Stack)) + u.LogDebug(atmosConfig, fmt.Sprintf("\nVariables for the component '%s' in the stack '%s':", info.ComponentFromArg, info.Stack)) - if cliConfig.Logs.Level == u.LogLevelTrace || cliConfig.Logs.Level == u.LogLevelDebug { - err = u.PrintAsYAMLToFileDescriptor(cliConfig, info.ComponentVarsSection) + if atmosConfig.Logs.Level == u.LogLevelTrace || atmosConfig.Logs.Level == u.LogLevelDebug { + err = u.PrintAsYAMLToFileDescriptor(atmosConfig, info.ComponentVarsSection) if err != nil { return err } } // Write the variables to file - u.LogDebug(cliConfig, "Writing the variables to file:") - u.LogDebug(cliConfig, varFilePath) + u.LogDebug(atmosConfig, "Writing the variables to file:") + u.LogDebug(atmosConfig, varFilePath) if !info.DryRun { err = u.WriteToFileAsYAML(varFilePath, info.ComponentVarsSection, 0644) diff --git a/internal/exec/help.go b/internal/exec/help.go index 60267c509..b90c8ce64 100644 --- a/internal/exec/help.go +++ b/internal/exec/help.go @@ -10,7 +10,7 @@ import ( // processHelp processes help commands func processHelp( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, componentType string, command string, ) error { diff --git a/internal/exec/oci_utils.go b/internal/exec/oci_utils.go index cb59dc968..49b591658 100644 --- a/internal/exec/oci_utils.go +++ b/internal/exec/oci_utils.go @@ -20,14 +20,14 @@ import ( ) // processOciImage downloads an Image from an OCI-compatible registry, extracts the layers from the tarball, and writes to the destination directory -func processOciImage(cliConfig schema.CliConfiguration, imageName string, destDir string) error { +func processOciImage(atmosConfig schema.AtmosConfiguration, imageName string, destDir string) error { // Temp directory for the tarball files tempDir, err := os.MkdirTemp("", uuid.New().String()) if err != nil { return err } - defer removeTempDir(cliConfig, tempDir) + defer removeTempDir(atmosConfig, tempDir) // Temp tarball file name tempTarFileName := filepath.Join(tempDir, uuid.New().String()) + ".tar" @@ -60,7 +60,7 @@ func processOciImage(cliConfig schema.CliConfiguration, imageName string, destDi m, err := tarball.LoadManifest(func() (io.ReadCloser, error) { f, err := os.Open(tempTarFileName) if err != nil { - u.LogError(cliConfig, err) + u.LogError(atmosConfig, err) return nil, err } return f, nil @@ -84,7 +84,7 @@ func processOciImage(cliConfig schema.CliConfiguration, imageName string, destDi // Extract the tarball layers into the temp directory // The tarball layers are tarballs themselves - err = extractTarball(cliConfig, tempTarFileName, tempDir) + err = extractTarball(atmosConfig, tempTarFileName, tempDir) if err != nil { return err } @@ -93,7 +93,7 @@ func processOciImage(cliConfig schema.CliConfiguration, imageName string, destDi for _, l := range manifest.Layers { layerPath := filepath.Join(tempDir, l) - err = extractTarball(cliConfig, layerPath, destDir) + err = extractTarball(atmosConfig, layerPath, destDir) if err != nil { return err } diff --git a/internal/exec/path_utils.go b/internal/exec/path_utils.go index c29660f60..554855487 100644 --- a/internal/exec/path_utils.go +++ b/internal/exec/path_utils.go @@ -8,10 +8,10 @@ import ( ) // constructTerraformComponentWorkingDir constructs the working dir for a terraform component in a stack -func constructTerraformComponentWorkingDir(cliConfig schema.CliConfiguration, info schema.ConfigAndStacksInfo) string { +func constructTerraformComponentWorkingDir(atmosConfig schema.AtmosConfiguration, info schema.ConfigAndStacksInfo) string { return filepath.Join( - cliConfig.BasePath, - cliConfig.Components.Terraform.BasePath, + atmosConfig.BasePath, + atmosConfig.Components.Terraform.BasePath, info.ComponentFolderPrefix, info.FinalComponent, ) @@ -42,7 +42,7 @@ func constructTerraformComponentVarfileName(info schema.ConfigAndStacksInfo) str } // constructTerraformComponentVarfilePath constructs the varfile path for a terraform component in a stack -func constructTerraformComponentVarfilePath(Config schema.CliConfiguration, info schema.ConfigAndStacksInfo) string { +func constructTerraformComponentVarfilePath(Config schema.AtmosConfiguration, info schema.ConfigAndStacksInfo) string { return filepath.Join( constructTerraformComponentWorkingDir(Config, info), constructTerraformComponentVarfileName(info), @@ -50,18 +50,18 @@ func constructTerraformComponentVarfilePath(Config schema.CliConfiguration, info } // constructTerraformComponentPlanfilePath constructs the planfile path for a terraform component in a stack -func constructTerraformComponentPlanfilePath(cliConfig schema.CliConfiguration, info schema.ConfigAndStacksInfo) string { +func constructTerraformComponentPlanfilePath(atmosConfig schema.AtmosConfiguration, info schema.ConfigAndStacksInfo) string { return filepath.Join( - constructTerraformComponentWorkingDir(cliConfig, info), + constructTerraformComponentWorkingDir(atmosConfig, info), constructTerraformComponentPlanfileName(info), ) } // constructHelmfileComponentWorkingDir constructs the working dir for a helmfile component in a stack -func constructHelmfileComponentWorkingDir(cliConfig schema.CliConfiguration, info schema.ConfigAndStacksInfo) string { +func constructHelmfileComponentWorkingDir(atmosConfig schema.AtmosConfiguration, info schema.ConfigAndStacksInfo) string { return filepath.Join( - cliConfig.BasePath, - cliConfig.Components.Helmfile.BasePath, + atmosConfig.BasePath, + atmosConfig.Components.Helmfile.BasePath, info.ComponentFolderPrefix, info.FinalComponent, ) @@ -79,9 +79,9 @@ func constructHelmfileComponentVarfileName(info schema.ConfigAndStacksInfo) stri } // constructHelmfileComponentVarfilePath constructs the varfile path for a helmfile component in a stack -func constructHelmfileComponentVarfilePath(cliConfig schema.CliConfiguration, info schema.ConfigAndStacksInfo) string { +func constructHelmfileComponentVarfilePath(atmosConfig schema.AtmosConfiguration, info schema.ConfigAndStacksInfo) string { return filepath.Join( - constructHelmfileComponentWorkingDir(cliConfig, info), + constructHelmfileComponentWorkingDir(atmosConfig, info), constructHelmfileComponentVarfileName(info), ) } diff --git a/internal/exec/pro.go b/internal/exec/pro.go index f6a221bc5..6048a6d1a 100644 --- a/internal/exec/pro.go +++ b/internal/exec/pro.go @@ -34,12 +34,12 @@ func parseLockUnlockCliArgs(cmd *cobra.Command, args []string) (ProLockUnlockCmd // InitCliConfig finds and merges CLI configurations in the following order: // system dir, home dir, current dir, ENV vars, command-line arguments - cliConfig, err := cfg.InitCliConfig(info, true) + atmosConfig, err := cfg.InitCliConfig(info, true) if err != nil { return ProLockUnlockCmdArgs{}, err } - logger, err := l.NewLoggerFromCliConfig(cliConfig) + logger, err := l.NewLoggerFromCliConfig(atmosConfig) if err != nil { return ProLockUnlockCmdArgs{}, err } diff --git a/internal/exec/shell_utils.go b/internal/exec/shell_utils.go index 885f4494d..fbf14a6f9 100644 --- a/internal/exec/shell_utils.go +++ b/internal/exec/shell_utils.go @@ -23,7 +23,7 @@ import ( // ExecuteShellCommand prints and executes the provided command with args and flags func ExecuteShellCommand( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, command string, args []string, dir string, @@ -50,22 +50,22 @@ func ExecuteShellCommand( } else { f, err := os.OpenFile(redirectStdError, os.O_WRONLY|os.O_CREATE, 0644) if err != nil { - u.LogWarning(cliConfig, err.Error()) + u.LogWarning(atmosConfig, err.Error()) return err } defer func(f *os.File) { err = f.Close() if err != nil { - u.LogWarning(cliConfig, err.Error()) + u.LogWarning(atmosConfig, err.Error()) } }(f) cmd.Stderr = f } - u.LogDebug(cliConfig, "\nExecuting command:") - u.LogDebug(cliConfig, cmd.String()) + u.LogDebug(atmosConfig, "\nExecuting command:") + u.LogDebug(atmosConfig, cmd.String()) if dryRun { return nil @@ -76,15 +76,15 @@ func ExecuteShellCommand( // ExecuteShell runs a shell script func ExecuteShell( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, command string, name string, dir string, env []string, dryRun bool, ) error { - u.LogDebug(cliConfig, "\nExecuting command:") - u.LogDebug(cliConfig, command) + u.LogDebug(atmosConfig, "\nExecuting command:") + u.LogDebug(atmosConfig, command) if dryRun { return nil @@ -95,7 +95,7 @@ func ExecuteShell( // ExecuteShellAndReturnOutput runs a shell script and capture its standard output func ExecuteShellAndReturnOutput( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, command string, name string, dir string, @@ -104,8 +104,8 @@ func ExecuteShellAndReturnOutput( ) (string, error) { var b bytes.Buffer - u.LogDebug(cliConfig, "\nExecuting command:") - u.LogDebug(cliConfig, command) + u.LogDebug(atmosConfig, "\nExecuting command:") + u.LogDebug(atmosConfig, command) if dryRun { return "", nil @@ -142,7 +142,7 @@ func shellRunner(command string, name string, dir string, env []string, out io.W // execTerraformShellCommand executes `terraform shell` command by starting a new interactive shell func execTerraformShellCommand( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, component string, stack string, componentEnvList []string, @@ -172,7 +172,7 @@ func execTerraformShellCommand( } val, err := strconv.Atoi(atmosShellLvl) if err != nil { - u.LogWarning(cliConfig, fmt.Sprintf("Failed to parse ATMOS_SHLVL: %v", err)) + u.LogWarning(atmosConfig, fmt.Sprintf("Failed to parse ATMOS_SHLVL: %v", err)) return } // Prevent negative values @@ -181,7 +181,7 @@ func execTerraformShellCommand( newVal = 0 } if err := os.Setenv("ATMOS_SHLVL", fmt.Sprintf("%d", newVal)); err != nil { - u.LogWarning(cliConfig, fmt.Sprintf("Failed to update ATMOS_SHLVL: %v", err)) + u.LogWarning(atmosConfig, fmt.Sprintf("Failed to update ATMOS_SHLVL: %v", err)) } }() @@ -199,10 +199,10 @@ func execTerraformShellCommand( componentEnvList = append(componentEnvList, fmt.Sprintf("ATMOS_SHELL_WORKING_DIR=%s", workingDir)) componentEnvList = append(componentEnvList, fmt.Sprintf("ATMOS_TERRAFORM_WORKSPACE=%s", workspaceName)) - hasCustomShellPrompt := cliConfig.Components.Terraform.Shell.Prompt != "" + hasCustomShellPrompt := atmosConfig.Components.Terraform.Shell.Prompt != "" if hasCustomShellPrompt { // Template for the custom shell prompt - tmpl := cliConfig.Components.Terraform.Shell.Prompt + tmpl := atmosConfig.Components.Terraform.Shell.Prompt // Data for the template data := struct { @@ -221,14 +221,14 @@ func execTerraformShellCommand( } } - u.LogDebug(cliConfig, "\nStarting a new interactive shell where you can execute all native Terraform commands (type 'exit' to go back)") - u.LogDebug(cliConfig, fmt.Sprintf("Component: %s\n", component)) - u.LogDebug(cliConfig, fmt.Sprintf("Stack: %s\n", stack)) - u.LogDebug(cliConfig, fmt.Sprintf("Working directory: %s\n", workingDir)) - u.LogDebug(cliConfig, fmt.Sprintf("Terraform workspace: %s\n", workspaceName)) - u.LogDebug(cliConfig, "\nSetting the ENV vars in the shell:\n") + u.LogDebug(atmosConfig, "\nStarting a new interactive shell where you can execute all native Terraform commands (type 'exit' to go back)") + u.LogDebug(atmosConfig, fmt.Sprintf("Component: %s\n", component)) + u.LogDebug(atmosConfig, fmt.Sprintf("Stack: %s\n", stack)) + u.LogDebug(atmosConfig, fmt.Sprintf("Working directory: %s\n", workingDir)) + u.LogDebug(atmosConfig, fmt.Sprintf("Terraform workspace: %s\n", workspaceName)) + u.LogDebug(atmosConfig, "\nSetting the ENV vars in the shell:\n") for _, v := range componentEnvList { - u.LogDebug(cliConfig, v) + u.LogDebug(atmosConfig, v) } // Transfer stdin, stdout, and stderr to the new process and also set the target directory for the shell to start in @@ -274,7 +274,7 @@ func execTerraformShellCommand( } } - u.LogDebug(cliConfig, fmt.Sprintf("Starting process: %s\n", shellCommand)) + u.LogDebug(atmosConfig, fmt.Sprintf("Starting process: %s\n", shellCommand)) args := strings.Fields(shellCommand) @@ -289,6 +289,6 @@ func execTerraformShellCommand( return err } - u.LogDebug(cliConfig, fmt.Sprintf("Exited shell: %s\n", state.String())) + u.LogDebug(atmosConfig, fmt.Sprintf("Exited shell: %s\n", state.String())) return nil } diff --git a/internal/exec/spacelift_utils.go b/internal/exec/spacelift_utils.go index d7e7480e0..584ad9371 100644 --- a/internal/exec/spacelift_utils.go +++ b/internal/exec/spacelift_utils.go @@ -83,7 +83,7 @@ func BuildSpaceliftStackNames(stacks map[string]any, stackNamePattern string) ([ // BuildSpaceliftStackNameFromComponentConfig builds Spacelift stack name from the component config func BuildSpaceliftStackNameFromComponentConfig( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, configAndStacksInfo schema.ConfigAndStacksInfo, ) (string, error) { @@ -101,13 +101,13 @@ func BuildSpaceliftStackNameFromComponentConfig( context := cfg.GetContextFromVars(configAndStacksInfo.ComponentVarsSection) context.Component = strings.Replace(configAndStacksInfo.ComponentFromArg, "/", "-", -1) - if cliConfig.Stacks.NameTemplate != "" { - contextPrefix, err = ProcessTmpl("name-template", cliConfig.Stacks.NameTemplate, configAndStacksInfo.ComponentSection, false) + if atmosConfig.Stacks.NameTemplate != "" { + contextPrefix, err = ProcessTmpl("name-template", atmosConfig.Stacks.NameTemplate, configAndStacksInfo.ComponentSection, false) if err != nil { return "", err } } else { - contextPrefix, err = cfg.GetContextPrefix(configAndStacksInfo.Stack, context, GetStackNamePattern(cliConfig), configAndStacksInfo.Stack) + contextPrefix, err = cfg.GetContextPrefix(configAndStacksInfo.Stack, context, GetStackNamePattern(atmosConfig), configAndStacksInfo.Stack) if err != nil { return "", err } diff --git a/internal/exec/stack_processor_utils.go b/internal/exec/stack_processor_utils.go index f64ee7f25..ea35c1cd3 100644 --- a/internal/exec/stack_processor_utils.go +++ b/internal/exec/stack_processor_utils.go @@ -31,7 +31,7 @@ var ( // ProcessYAMLConfigFiles takes a list of paths to stack manifests, processes and deep-merges all imports, // and returns a list of stack configs func ProcessYAMLConfigFiles( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, stacksBasePath string, terraformComponentsBasePath string, helmfileComponentsBasePath string, @@ -71,7 +71,7 @@ func ProcessYAMLConfigFiles( ) deepMergedStackConfig, importsConfig, stackConfig, _, _, err := ProcessYAMLConfigFile( - cliConfig, + atmosConfig, stackBasePath, p, map[string]map[string]any{}, @@ -101,7 +101,7 @@ func ProcessYAMLConfigFiles( componentStackMap := map[string]map[string][]string{} finalConfig, err := ProcessStackConfig( - cliConfig, + atmosConfig, stackBasePath, terraformComponentsBasePath, helmfileComponentsBasePath, @@ -151,7 +151,7 @@ func ProcessYAMLConfigFiles( // recursively processes and deep-merges all imports, // and returns the final stack config func ProcessYAMLConfigFile( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, basePath string, filePath string, importsConfig map[string]map[string]any, @@ -213,7 +213,7 @@ func ProcessYAMLConfigFile( if !skipTemplatesProcessingInImports && len(context) > 0 { stackManifestTemplatesProcessed, err = ProcessTmpl(relativeFilePath, stackYamlConfig, context, ignoreMissingTemplateValues) if err != nil { - if cliConfig.Logs.Level == u.LogLevelTrace || cliConfig.Logs.Level == u.LogLevelDebug { + if atmosConfig.Logs.Level == u.LogLevelTrace || atmosConfig.Logs.Level == u.LogLevelDebug { stackManifestTemplatesErrorMessage = fmt.Sprintf("\n\n%s", stackYamlConfig) } e := fmt.Errorf("invalid stack manifest '%s'\n%v%s", relativeFilePath, err, stackManifestTemplatesErrorMessage) @@ -223,7 +223,7 @@ func ProcessYAMLConfigFile( stackConfigMap, err := u.UnmarshalYAML[schema.AtmosSectionMapType](stackManifestTemplatesProcessed) if err != nil { - if cliConfig.Logs.Level == u.LogLevelTrace || cliConfig.Logs.Level == u.LogLevelDebug { + if atmosConfig.Logs.Level == u.LogLevelTrace || atmosConfig.Logs.Level == u.LogLevelDebug { stackManifestTemplatesErrorMessage = fmt.Sprintf("\n\n%s", stackYamlConfig) } e := fmt.Errorf("invalid stack manifest '%s'\n%v%s", relativeFilePath, err, stackManifestTemplatesErrorMessage) @@ -315,7 +315,7 @@ func ProcessYAMLConfigFile( // Final Terraform `overrides` finalTerraformOverrides, err = m.Merge( - cliConfig, + atmosConfig, []map[string]any{globalOverrides, terraformOverrides, parentTerraformOverrides}, ) if err != nil { @@ -324,7 +324,7 @@ func ProcessYAMLConfigFile( // Final Helmfile `overrides` finalHelmfileOverrides, err = m.Merge( - cliConfig, + atmosConfig, []map[string]any{globalOverrides, helmfileOverrides, parentHelmfileOverrides}, ) if err != nil { @@ -425,7 +425,7 @@ func ProcessYAMLConfigFile( // The parent `context` takes precedence over the current (imported) `context` and will override items with the same keys. // TODO: instead of calling the conversion functions, we need to switch to generics and update everything to support it listOfMaps := []map[string]any{importStruct.Context, context} - mergedContext, err := m.Merge(cliConfig, listOfMaps) + mergedContext, err := m.Merge(atmosConfig, listOfMaps) if err != nil { return nil, nil, nil, nil, nil, err } @@ -433,7 +433,7 @@ func ProcessYAMLConfigFile( // Process the imports in the current manifest for _, importFile := range importMatches { yamlConfig, _, yamlConfigRaw, importTerraformOverrides, importHelmfileOverrides, err2 := ProcessYAMLConfigFile( - cliConfig, + atmosConfig, basePath, importFile, importsConfig, @@ -454,7 +454,7 @@ func ProcessYAMLConfigFile( // Final Terraform `overrides` finalTerraformOverrides, err = m.Merge( - cliConfig, + atmosConfig, []map[string]any{importTerraformOverrides, finalTerraformOverrides}, ) if err != nil { @@ -463,7 +463,7 @@ func ProcessYAMLConfigFile( // Final Helmfile `overrides` finalHelmfileOverrides, err = m.Merge( - cliConfig, + atmosConfig, []map[string]any{importHelmfileOverrides, finalHelmfileOverrides}, ) if err != nil { @@ -513,7 +513,7 @@ func ProcessYAMLConfigFile( } // Deep-merge the stack manifest and all the imports - stackConfigsDeepMerged, err := m.Merge(cliConfig, stackConfigs) + stackConfigsDeepMerged, err := m.Merge(atmosConfig, stackConfigs) if err != nil { err2 := fmt.Errorf("ProcessYAMLConfigFile: Merge: Deep-merge the stack manifest and all the imports: Error: %v", err) return nil, nil, nil, nil, nil, err2 @@ -525,7 +525,7 @@ func ProcessYAMLConfigFile( // ProcessStackConfig takes a stack manifest, deep-merges all variables, settings, environments and backends, // and returns the final stack configuration for all Terraform and helmfile components func ProcessStackConfig( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, stacksBasePath string, terraformComponentsBasePath string, helmfileComponentsBasePath string, @@ -626,7 +626,7 @@ func ProcessStackConfig( } } - globalAndTerraformVars, err := m.Merge(cliConfig, []map[string]any{globalVarsSection, terraformVars}) + globalAndTerraformVars, err := m.Merge(atmosConfig, []map[string]any{globalVarsSection, terraformVars}) if err != nil { return nil, err } @@ -638,7 +638,7 @@ func ProcessStackConfig( } } - globalAndTerraformSettings, err := m.Merge(cliConfig, []map[string]any{globalSettingsSection, terraformSettings}) + globalAndTerraformSettings, err := m.Merge(atmosConfig, []map[string]any{globalSettingsSection, terraformSettings}) if err != nil { return nil, err } @@ -650,7 +650,7 @@ func ProcessStackConfig( } } - globalAndTerraformEnv, err := m.Merge(cliConfig, []map[string]any{globalEnvSection, terraformEnv}) + globalAndTerraformEnv, err := m.Merge(atmosConfig, []map[string]any{globalEnvSection, terraformEnv}) if err != nil { return nil, err } @@ -713,7 +713,7 @@ func ProcessStackConfig( } } - globalAndHelmfileVars, err := m.Merge(cliConfig, []map[string]any{globalVarsSection, helmfileVars}) + globalAndHelmfileVars, err := m.Merge(atmosConfig, []map[string]any{globalVarsSection, helmfileVars}) if err != nil { return nil, err } @@ -725,7 +725,7 @@ func ProcessStackConfig( } } - globalAndHelmfileSettings, err := m.Merge(cliConfig, []map[string]any{globalSettingsSection, helmfileSettings}) + globalAndHelmfileSettings, err := m.Merge(atmosConfig, []map[string]any{globalSettingsSection, helmfileSettings}) if err != nil { return nil, err } @@ -737,7 +737,7 @@ func ProcessStackConfig( } } - globalAndHelmfileEnv, err := m.Merge(cliConfig, []map[string]any{globalEnvSection, helmfileEnv}) + globalAndHelmfileEnv, err := m.Merge(atmosConfig, []map[string]any{globalEnvSection, helmfileEnv}) if err != nil { return nil, err } @@ -920,7 +920,7 @@ func ProcessStackConfig( // Process the base components recursively to find `componentInheritanceChain` err = ProcessBaseComponentConfig( - cliConfig, + atmosConfig, &baseComponentConfig, allTerraformComponentsMap, component, @@ -988,7 +988,7 @@ func ProcessStackConfig( // Process the baseComponentFromInheritList components recursively to find `componentInheritanceChain` err = ProcessBaseComponentConfig( - cliConfig, + atmosConfig, &baseComponentConfig, allTerraformComponentsMap, component, @@ -1019,7 +1019,7 @@ func ProcessStackConfig( // Final configs finalComponentVars, err := m.Merge( - cliConfig, + atmosConfig, []map[string]any{ globalAndTerraformVars, baseComponentVars, @@ -1031,7 +1031,7 @@ func ProcessStackConfig( } finalComponentSettings, err := m.Merge( - cliConfig, + atmosConfig, []map[string]any{ globalAndTerraformSettings, baseComponentSettings, @@ -1043,7 +1043,7 @@ func ProcessStackConfig( } finalComponentEnv, err := m.Merge( - cliConfig, + atmosConfig, []map[string]any{ globalAndTerraformEnv, baseComponentEnv, @@ -1055,7 +1055,7 @@ func ProcessStackConfig( } finalComponentProviders, err := m.Merge( - cliConfig, + atmosConfig, []map[string]any{ terraformProviders, baseComponentProviders, @@ -1076,7 +1076,7 @@ func ProcessStackConfig( } finalComponentBackendSection, err := m.Merge( - cliConfig, + atmosConfig, []map[string]any{ globalBackendSection, baseComponentBackendSection, @@ -1160,7 +1160,7 @@ func ProcessStackConfig( } finalComponentRemoteStateBackendSection, err := m.Merge( - cliConfig, + atmosConfig, []map[string]any{ globalRemoteStateBackendSection, baseComponentRemoteStateBackendSection, @@ -1173,7 +1173,7 @@ func ProcessStackConfig( // Merge `backend` and `remote_state_backend` sections // This will allow keeping `remote_state_backend` section DRY finalComponentRemoteStateBackendSectionMerged, err := m.Merge( - cliConfig, + atmosConfig, []map[string]any{ finalComponentBackendSection, finalComponentRemoteStateBackendSection, @@ -1198,8 +1198,8 @@ func ProcessStackConfig( // - component `command` section // - `overrides.command` section finalComponentTerraformCommand := "terraform" - if cliConfig.Components.Terraform.Command != "" { - finalComponentTerraformCommand = cliConfig.Components.Terraform.Command + if atmosConfig.Components.Terraform.Command != "" { + finalComponentTerraformCommand = atmosConfig.Components.Terraform.Command } if terraformCommand != "" { finalComponentTerraformCommand = terraformCommand @@ -1236,7 +1236,7 @@ func ProcessStackConfig( } } - finalSettings, err := processSettingsIntegrationsGithub(cliConfig, finalComponentSettings) + finalSettings, err := processSettingsIntegrationsGithub(atmosConfig, finalComponentSettings) if err != nil { return nil, err } @@ -1379,7 +1379,7 @@ func ProcessStackConfig( // Process the base components recursively to find `componentInheritanceChain` err = ProcessBaseComponentConfig( - cliConfig, + atmosConfig, &baseComponentConfig, allHelmfileComponentsMap, component, @@ -1442,7 +1442,7 @@ func ProcessStackConfig( // Process the baseComponentFromInheritList components recursively to find `componentInheritanceChain` err = ProcessBaseComponentConfig( - cliConfig, + atmosConfig, &baseComponentConfig, allHelmfileComponentsMap, component, @@ -1470,7 +1470,7 @@ func ProcessStackConfig( // Final configs finalComponentVars, err := m.Merge( - cliConfig, + atmosConfig, []map[string]any{ globalAndHelmfileVars, baseComponentVars, @@ -1482,7 +1482,7 @@ func ProcessStackConfig( } finalComponentSettings, err := m.Merge( - cliConfig, + atmosConfig, []map[string]any{ globalAndHelmfileSettings, baseComponentSettings, @@ -1494,7 +1494,7 @@ func ProcessStackConfig( } finalComponentEnv, err := m.Merge( - cliConfig, + atmosConfig, []map[string]any{ globalAndHelmfileEnv, baseComponentEnv, @@ -1513,8 +1513,8 @@ func ProcessStackConfig( // - component `command` section // - `overrides.command` section finalComponentHelmfileCommand := "helmfile" - if cliConfig.Components.Helmfile.Command != "" { - finalComponentHelmfileCommand = cliConfig.Components.Helmfile.Command + if atmosConfig.Components.Helmfile.Command != "" { + finalComponentHelmfileCommand = atmosConfig.Components.Helmfile.Command } if helmfileCommand != "" { finalComponentHelmfileCommand = helmfileCommand @@ -1529,7 +1529,7 @@ func ProcessStackConfig( finalComponentHelmfileCommand = componentOverridesHelmfileCommand } - finalSettings, err := processSettingsIntegrationsGithub(cliConfig, finalComponentSettings) + finalSettings, err := processSettingsIntegrationsGithub(atmosConfig, finalComponentSettings) if err != nil { return nil, err } @@ -1564,7 +1564,7 @@ func ProcessStackConfig( // processSettingsIntegrationsGithub deep-merges the `settings.integrations.github` section from stack manifests with // the `integrations.github` section from `atmos.yaml` -func processSettingsIntegrationsGithub(cliConfig schema.CliConfiguration, settings map[string]any) (map[string]any, error) { +func processSettingsIntegrationsGithub(atmosConfig schema.AtmosConfiguration, settings map[string]any) (map[string]any, error) { settingsIntegrationsSection := make(map[string]any) settingsIntegrationsGithubSection := make(map[string]any) @@ -1582,9 +1582,9 @@ func processSettingsIntegrationsGithub(cliConfig schema.CliConfiguration, settin // deep-merge the `settings.integrations.github` section from stack manifests with the `integrations.github` section from `atmos.yaml` settingsIntegrationsGithubMerged, err := m.Merge( - cliConfig, + atmosConfig, []map[string]any{ - cliConfig.Integrations.GitHub, + atmosConfig.Integrations.GitHub, settingsIntegrationsGithubSection, }) if err != nil { @@ -1811,7 +1811,7 @@ func sectionContainsAnyNotEmptySections(section map[string]any, sectionsToCheck // CreateComponentStackMap accepts a config file and creates a map of component-stack dependencies func CreateComponentStackMap( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, stacksBasePath string, terraformComponentsBasePath string, helmfileComponentsBasePath string, @@ -1843,7 +1843,7 @@ func CreateComponentStackMap( if !isDirectory && isYaml { config, _, _, _, _, err := ProcessYAMLConfigFile( - cliConfig, + atmosConfig, stacksBasePath, p, map[string]map[string]any{}, @@ -1861,7 +1861,7 @@ func CreateComponentStackMap( } finalConfig, err := ProcessStackConfig( - cliConfig, + atmosConfig, stacksBasePath, terraformComponentsBasePath, helmfileComponentsBasePath, @@ -1940,7 +1940,7 @@ func GetFileContent(filePath string) (string, error) { // ProcessBaseComponentConfig processes base component(s) config func ProcessBaseComponentConfig( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, baseComponentConfig *schema.BaseComponentConfig, allComponentsMap map[string]any, component string, @@ -1991,7 +1991,7 @@ func ProcessBaseComponentConfig( } err := ProcessBaseComponentConfig( - cliConfig, + atmosConfig, baseComponentConfig, allComponentsMap, baseComponent, @@ -2037,7 +2037,7 @@ func ProcessBaseComponentConfig( // Process the baseComponentFromInheritList components recursively to find `componentInheritanceChain` err := ProcessBaseComponentConfig( - cliConfig, + atmosConfig, baseComponentConfig, allComponentsMap, component, @@ -2125,28 +2125,28 @@ func ProcessBaseComponentConfig( } // Base component `vars` - merged, err := m.Merge(cliConfig, []map[string]any{baseComponentConfig.BaseComponentVars, baseComponentVars}) + merged, err := m.Merge(atmosConfig, []map[string]any{baseComponentConfig.BaseComponentVars, baseComponentVars}) if err != nil { return err } baseComponentConfig.BaseComponentVars = merged // Base component `settings` - merged, err = m.Merge(cliConfig, []map[string]any{baseComponentConfig.BaseComponentSettings, baseComponentSettings}) + merged, err = m.Merge(atmosConfig, []map[string]any{baseComponentConfig.BaseComponentSettings, baseComponentSettings}) if err != nil { return err } baseComponentConfig.BaseComponentSettings = merged // Base component `env` - merged, err = m.Merge(cliConfig, []map[string]any{baseComponentConfig.BaseComponentEnv, baseComponentEnv}) + merged, err = m.Merge(atmosConfig, []map[string]any{baseComponentConfig.BaseComponentEnv, baseComponentEnv}) if err != nil { return err } baseComponentConfig.BaseComponentEnv = merged // Base component `providers` - merged, err = m.Merge(cliConfig, []map[string]any{baseComponentConfig.BaseComponentProviders, baseComponentProviders}) + merged, err = m.Merge(atmosConfig, []map[string]any{baseComponentConfig.BaseComponentProviders, baseComponentProviders}) if err != nil { return err } @@ -2159,7 +2159,7 @@ func ProcessBaseComponentConfig( baseComponentConfig.BaseComponentBackendType = baseComponentBackendType // Base component `backend` - merged, err = m.Merge(cliConfig, []map[string]any{baseComponentConfig.BaseComponentBackendSection, baseComponentBackendSection}) + merged, err = m.Merge(atmosConfig, []map[string]any{baseComponentConfig.BaseComponentBackendSection, baseComponentBackendSection}) if err != nil { return err } @@ -2169,7 +2169,7 @@ func ProcessBaseComponentConfig( baseComponentConfig.BaseComponentRemoteStateBackendType = baseComponentRemoteStateBackendType // Base component `remote_state_backend` - merged, err = m.Merge(cliConfig, []map[string]any{baseComponentConfig.BaseComponentRemoteStateBackendSection, baseComponentRemoteStateBackendSection}) + merged, err = m.Merge(atmosConfig, []map[string]any{baseComponentConfig.BaseComponentRemoteStateBackendSection, baseComponentRemoteStateBackendSection}) if err != nil { return err } diff --git a/internal/exec/stack_utils.go b/internal/exec/stack_utils.go index 117ba2900..96fa24b9e 100644 --- a/internal/exec/stack_utils.go +++ b/internal/exec/stack_utils.go @@ -11,19 +11,19 @@ import ( ) // BuildTerraformWorkspace builds Terraform workspace -func BuildTerraformWorkspace(cliConfig schema.CliConfiguration, configAndStacksInfo schema.ConfigAndStacksInfo) (string, error) { +func BuildTerraformWorkspace(atmosConfig schema.AtmosConfiguration, configAndStacksInfo schema.ConfigAndStacksInfo) (string, error) { var contextPrefix string var err error var tmpl string - if cliConfig.Stacks.NameTemplate != "" { - tmpl, err = ProcessTmpl("terraform-workspace-stacks-name-template", cliConfig.Stacks.NameTemplate, configAndStacksInfo.ComponentSection, false) + if atmosConfig.Stacks.NameTemplate != "" { + tmpl, err = ProcessTmpl("terraform-workspace-stacks-name-template", atmosConfig.Stacks.NameTemplate, configAndStacksInfo.ComponentSection, false) if err != nil { return "", err } contextPrefix = tmpl - } else if cliConfig.Stacks.NamePattern != "" { - contextPrefix, err = cfg.GetContextPrefix(configAndStacksInfo.Stack, configAndStacksInfo.Context, cliConfig.Stacks.NamePattern, configAndStacksInfo.Stack) + } else if atmosConfig.Stacks.NamePattern != "" { + contextPrefix, err = cfg.GetContextPrefix(configAndStacksInfo.Stack, configAndStacksInfo.Context, atmosConfig.Stacks.NamePattern, configAndStacksInfo.Stack) if err != nil { return "", err } @@ -155,7 +155,7 @@ func BuildDependentStackNameFromDependsOn( // BuildComponentPath builds component path (path to the component's physical location on disk) func BuildComponentPath( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, componentSectionMap map[string]any, componentType string, ) string { @@ -164,9 +164,9 @@ func BuildComponentPath( if stackComponentSection, ok := componentSectionMap[cfg.ComponentSectionName].(string); ok { if componentType == "terraform" { - componentPath = filepath.Join(cliConfig.BasePath, cliConfig.Components.Terraform.BasePath, stackComponentSection) + componentPath = filepath.Join(atmosConfig.BasePath, atmosConfig.Components.Terraform.BasePath, stackComponentSection) } else if componentType == "helmfile" { - componentPath = filepath.Join(cliConfig.BasePath, cliConfig.Components.Helmfile.BasePath, stackComponentSection) + componentPath = filepath.Join(atmosConfig.BasePath, atmosConfig.Components.Helmfile.BasePath, stackComponentSection) } } @@ -174,8 +174,8 @@ func BuildComponentPath( } // GetStackNamePattern returns stack name pattern -func GetStackNamePattern(cliConfig schema.CliConfiguration) string { - return cliConfig.Stacks.NamePattern +func GetStackNamePattern(atmosConfig schema.AtmosConfiguration) string { + return atmosConfig.Stacks.NamePattern } // IsComponentAbstract returns 'true' if the component is abstract diff --git a/internal/exec/tar_utils.go b/internal/exec/tar_utils.go index 20c9814e4..bcd1f1392 100644 --- a/internal/exec/tar_utils.go +++ b/internal/exec/tar_utils.go @@ -14,7 +14,7 @@ import ( ) // extractTarball extracts the tarball file into the destination directory -func extractTarball(cliConfig schema.CliConfiguration, sourceFile, extractPath string) error { +func extractTarball(atmosConfig schema.AtmosConfiguration, sourceFile, extractPath string) error { file, err := os.Open(sourceFile) if err != nil { return err @@ -42,7 +42,7 @@ func extractTarball(cliConfig schema.CliConfiguration, sourceFile, extractPath s } if strings.Contains(header.Name, "..") { - u.LogTrace(cliConfig, fmt.Sprintf("the header '%s' in the tarball '%s' contains '..', "+ + u.LogTrace(atmosConfig, fmt.Sprintf("the header '%s' in the tarball '%s' contains '..', "+ "which can lead to directory traversal attacks or overriding arbitrary files and directories.", header.Name, sourceFile)) continue @@ -84,7 +84,7 @@ func extractTarball(cliConfig schema.CliConfiguration, sourceFile, extractPath s } default: - u.LogTrace(cliConfig, fmt.Sprintf("the header '%s' in the tarball '%s' has unsupported header type '%v'. "+ + u.LogTrace(atmosConfig, fmt.Sprintf("the header '%s' in the tarball '%s' has unsupported header type '%v'. "+ "Supported header types are 'Directory' and 'File'", header.Name, sourceFile, header.Typeflag)) } diff --git a/internal/exec/template_funcs.go b/internal/exec/template_funcs.go index 010156a95..308be4e09 100644 --- a/internal/exec/template_funcs.go +++ b/internal/exec/template_funcs.go @@ -16,8 +16,8 @@ import ( ) // FuncMap creates and returns a map of template functions -func FuncMap(cliConfig schema.CliConfiguration, ctx context.Context, gomplateData *data.Data) template.FuncMap { - atmosFuncs := &AtmosFuncs{cliConfig, ctx, gomplateData} +func FuncMap(atmosConfig schema.AtmosConfiguration, ctx context.Context, gomplateData *data.Data) template.FuncMap { + atmosFuncs := &AtmosFuncs{atmosConfig, ctx, gomplateData} return map[string]any{ "atmos": func() any { return atmosFuncs }, @@ -25,15 +25,15 @@ func FuncMap(cliConfig schema.CliConfiguration, ctx context.Context, gomplateDat } type AtmosFuncs struct { - cliConfig schema.CliConfiguration + atmosConfig schema.AtmosConfiguration ctx context.Context gomplateData *data.Data } func (f AtmosFuncs) Component(component string, stack string) (any, error) { - return componentFunc(f.cliConfig, component, stack) + return componentFunc(f.atmosConfig, component, stack) } func (f AtmosFuncs) GomplateDatasource(alias string, args ...string) (any, error) { - return gomplateDatasourceFunc(f.cliConfig, alias, f.gomplateData, args...) + return gomplateDatasourceFunc(f.atmosConfig, alias, f.gomplateData, args...) } diff --git a/internal/exec/template_funcs_component.go b/internal/exec/template_funcs_component.go index 6e33b5ee7..fcea63683 100644 --- a/internal/exec/template_funcs_component.go +++ b/internal/exec/template_funcs_component.go @@ -14,24 +14,24 @@ var ( componentFuncSyncMap = sync.Map{} ) -func componentFunc(cliConfig schema.CliConfiguration, component string, stack string) (any, error) { - u.LogTrace(cliConfig, fmt.Sprintf("Executing template function 'atmos.Component(%s, %s)'", component, stack)) +func componentFunc(atmosConfig schema.AtmosConfiguration, component string, stack string) (any, error) { + u.LogTrace(atmosConfig, fmt.Sprintf("Executing template function 'atmos.Component(%s, %s)'", component, stack)) stackSlug := fmt.Sprintf("%s-%s", stack, component) // If the result for the component in the stack already exists in the cache, return it existingSections, found := componentFuncSyncMap.Load(stackSlug) if found && existingSections != nil { - if cliConfig.Logs.Level == u.LogLevelTrace { - u.LogTrace(cliConfig, fmt.Sprintf("Found the result of the template function 'atmos.Component(%s, %s)' in the cache", component, stack)) + if atmosConfig.Logs.Level == u.LogLevelTrace { + u.LogTrace(atmosConfig, fmt.Sprintf("Found the result of the template function 'atmos.Component(%s, %s)' in the cache", component, stack)) if outputsSection, ok := existingSections.(map[string]any)["outputs"]; ok { - u.LogTrace(cliConfig, "'outputs' section:") + u.LogTrace(atmosConfig, "'outputs' section:") y, err2 := u.ConvertToYAML(outputsSection) if err2 != nil { - u.LogError(cliConfig, err2) + u.LogError(atmosConfig, err2) } else { - u.LogTrace(cliConfig, y) + u.LogTrace(atmosConfig, y) } } } @@ -57,7 +57,7 @@ func componentFunc(cliConfig schema.CliConfiguration, component string, stack st terraformOutputs = remoteStateBackendStaticTypeOutputs } else { // Execute `terraform output` - terraformOutputs, err = execTerraformOutput(cliConfig, component, stack, sections) + terraformOutputs, err = execTerraformOutput(atmosConfig, component, stack, sections) if err != nil { return nil, err } @@ -72,13 +72,13 @@ func componentFunc(cliConfig schema.CliConfiguration, component string, stack st // Cache the result componentFuncSyncMap.Store(stackSlug, sections) - if cliConfig.Logs.Level == u.LogLevelTrace { - u.LogTrace(cliConfig, fmt.Sprintf("Executed template function 'atmos.Component(%s, %s)'\n\n'outputs' section:", component, stack)) + if atmosConfig.Logs.Level == u.LogLevelTrace { + u.LogTrace(atmosConfig, fmt.Sprintf("Executed template function 'atmos.Component(%s, %s)'\n\n'outputs' section:", component, stack)) y, err2 := u.ConvertToYAML(terraformOutputs) if err2 != nil { - u.LogError(cliConfig, err2) + u.LogError(atmosConfig, err2) } else { - u.LogTrace(cliConfig, y) + u.LogTrace(atmosConfig, y) } } diff --git a/internal/exec/template_funcs_gomplate_datasource.go b/internal/exec/template_funcs_gomplate_datasource.go index ac8c9ba56..318de5400 100644 --- a/internal/exec/template_funcs_gomplate_datasource.go +++ b/internal/exec/template_funcs_gomplate_datasource.go @@ -13,8 +13,8 @@ var ( gomplateDatasourceFuncSyncMap = sync.Map{} ) -func gomplateDatasourceFunc(cliConfig schema.CliConfiguration, alias string, gomplateData *data.Data, args ...string) (any, error) { - u.LogTrace(cliConfig, fmt.Sprintf("atmos.GomplateDatasource(): processing datasource alias '%s'", alias)) +func gomplateDatasourceFunc(atmosConfig schema.AtmosConfiguration, alias string, gomplateData *data.Data, args ...string) (any, error) { + u.LogTrace(atmosConfig, fmt.Sprintf("atmos.GomplateDatasource(): processing datasource alias '%s'", alias)) // If the result for the alias already exists in the cache, return it existingResult, found := gomplateDatasourceFuncSyncMap.Load(alias) @@ -30,7 +30,7 @@ func gomplateDatasourceFunc(cliConfig schema.CliConfiguration, alias string, gom // Cache the result gomplateDatasourceFuncSyncMap.Store(alias, result) - u.LogTrace(cliConfig, fmt.Sprintf("atmos.GomplateDatasource(): processed datasource alias '%s'.\nResult: '%v'", alias, result)) + u.LogTrace(atmosConfig, fmt.Sprintf("atmos.GomplateDatasource(): processed datasource alias '%s'.\nResult: '%v'", alias, result)) return result, nil } diff --git a/internal/exec/template_utils.go b/internal/exec/template_utils.go index 3d41c187e..2ecc969d4 100644 --- a/internal/exec/template_utils.go +++ b/internal/exec/template_utils.go @@ -31,7 +31,7 @@ func ProcessTmpl( ctx := context.TODO() // Add Gomplate, Sprig and Atmos template functions - funcs := lo.Assign(gomplate.CreateFuncs(ctx, &d), sprig.FuncMap(), FuncMap(schema.CliConfiguration{}, ctx, &d)) + funcs := lo.Assign(gomplate.CreateFuncs(ctx, &d), sprig.FuncMap(), FuncMap(schema.AtmosConfiguration{}, ctx, &d)) t, err := template.New(tmplName).Funcs(funcs).Parse(tmplValue) if err != nil { @@ -62,26 +62,26 @@ func ProcessTmpl( // ProcessTmplWithDatasources parses and executes Go templates with datasources func ProcessTmplWithDatasources( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, settingsSection schema.Settings, tmplName string, tmplValue string, tmplData any, ignoreMissingTemplateValues bool, ) (string, error) { - if !cliConfig.Templates.Settings.Enabled { - u.LogTrace(cliConfig, fmt.Sprintf("ProcessTmplWithDatasources: not processing template '%s' since templating is disabled in 'atmos.yaml'", tmplName)) + if !atmosConfig.Templates.Settings.Enabled { + u.LogTrace(atmosConfig, fmt.Sprintf("ProcessTmplWithDatasources: not processing template '%s' since templating is disabled in 'atmos.yaml'", tmplName)) return tmplValue, nil } - u.LogTrace(cliConfig, fmt.Sprintf("ProcessTmplWithDatasources(): processing template '%s'", tmplName)) + u.LogTrace(atmosConfig, fmt.Sprintf("ProcessTmplWithDatasources(): processing template '%s'", tmplName)) // Merge the template settings from `atmos.yaml` CLI config and from the stack manifests var cliConfigTemplateSettingsMap map[string]any var stackManifestTemplateSettingsMap map[string]any var templateSettings schema.TemplatesSettings - err := mapstructure.Decode(cliConfig.Templates.Settings, &cliConfigTemplateSettingsMap) + err := mapstructure.Decode(atmosConfig.Templates.Settings, &cliConfigTemplateSettingsMap) if err != nil { return "", err } @@ -91,7 +91,7 @@ func ProcessTmplWithDatasources( return "", err } - templateSettingsMerged, err := merge.Merge(cliConfig, []map[string]any{cliConfigTemplateSettingsMap, stackManifestTemplateSettingsMap}) + templateSettingsMerged, err := merge.Merge(atmosConfig, []map[string]any{cliConfigTemplateSettingsMap, stackManifestTemplateSettingsMap}) if err != nil { return "", err } @@ -105,16 +105,16 @@ func ProcessTmplWithDatasources( funcs := make(map[string]any) // Number of processing evaluations/passes - evaluations, _ := lo.Coalesce(cliConfig.Templates.Settings.Evaluations, 1) + evaluations, _ := lo.Coalesce(atmosConfig.Templates.Settings.Evaluations, 1) result := tmplValue for i := 0; i < evaluations; i++ { - u.LogTrace(cliConfig, fmt.Sprintf("ProcessTmplWithDatasources(): template '%s' - evaluation %d", tmplName, i+1)) + u.LogTrace(atmosConfig, fmt.Sprintf("ProcessTmplWithDatasources(): template '%s' - evaluation %d", tmplName, i+1)) d := data.Data{} // Gomplate functions and datasources - if cliConfig.Templates.Settings.Gomplate.Enabled { + if atmosConfig.Templates.Settings.Gomplate.Enabled { // If timeout is not provided in `atmos.yaml` nor in `settings.templates.settings` stack manifest, use 5 seconds timeoutSeconds, _ := lo.Coalesce(templateSettings.Gomplate.Timeout, 5) @@ -140,12 +140,12 @@ func ProcessTmplWithDatasources( } // Sprig functions - if cliConfig.Templates.Settings.Sprig.Enabled { + if atmosConfig.Templates.Settings.Sprig.Enabled { funcs = lo.Assign(funcs, sprig.FuncMap()) } // Atmos functions - funcs = lo.Assign(funcs, FuncMap(cliConfig, context.TODO(), &d)) + funcs = lo.Assign(funcs, FuncMap(atmosConfig, context.TODO(), &d)) // Process and add environment variables for k, v := range templateSettings.Env { @@ -162,25 +162,25 @@ func ProcessTmplWithDatasources( leftDelimiter := "{{" rightDelimiter := "}}" - if len(cliConfig.Templates.Settings.Delimiters) > 0 { + if len(atmosConfig.Templates.Settings.Delimiters) > 0 { delimiterError := fmt.Errorf("invalid 'templates.settings.delimiters' config in 'atmos.yaml': %v\n"+ "'delimiters' must be an array with two string items: left and right delimiter\n"+ - "the left and right delimiters must not be an empty string", cliConfig.Templates.Settings.Delimiters) + "the left and right delimiters must not be an empty string", atmosConfig.Templates.Settings.Delimiters) - if len(cliConfig.Templates.Settings.Delimiters) != 2 { + if len(atmosConfig.Templates.Settings.Delimiters) != 2 { return "", delimiterError } - if cliConfig.Templates.Settings.Delimiters[0] == "" { + if atmosConfig.Templates.Settings.Delimiters[0] == "" { return "", delimiterError } - if cliConfig.Templates.Settings.Delimiters[1] == "" { + if atmosConfig.Templates.Settings.Delimiters[1] == "" { return "", delimiterError } - leftDelimiter = cliConfig.Templates.Settings.Delimiters[0] - rightDelimiter = cliConfig.Templates.Settings.Delimiters[1] + leftDelimiter = atmosConfig.Templates.Settings.Delimiters[0] + rightDelimiter = atmosConfig.Templates.Settings.Delimiters[1] } t.Delims(leftDelimiter, rightDelimiter) @@ -229,7 +229,7 @@ func ProcessTmplWithDatasources( } } - u.LogTrace(cliConfig, fmt.Sprintf("ProcessTmplWithDatasources(): processed template '%s'", tmplName)) + u.LogTrace(atmosConfig, fmt.Sprintf("ProcessTmplWithDatasources(): processed template '%s'", tmplName)) return result, nil } diff --git a/internal/exec/terraform.go b/internal/exec/terraform.go index 88fd45b04..fcf65bdb3 100644 --- a/internal/exec/terraform.go +++ b/internal/exec/terraform.go @@ -36,7 +36,7 @@ func ExecuteTerraformCmd(cmd *cobra.Command, args []string, additionalArgsAndFla // ExecuteTerraform executes terraform commands func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { - cliConfig, err := cfg.InitCliConfig(info, true) + atmosConfig, err := cfg.InitCliConfig(info, true) if err != nil { return err } @@ -53,7 +53,7 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { return err } - err = processHelp(cliConfig, "terraform", "") + err = processHelp(atmosConfig, "terraform", "") if err != nil { return err } @@ -62,7 +62,7 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { return nil } if info.SubCommand == "version" { - return ExecuteShellCommand(cliConfig, + return ExecuteShellCommand(atmosConfig, "terraform", []string{info.SubCommand}, "", @@ -87,7 +87,7 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { } if shouldProcessStacks { - info, err = ProcessStacks(cliConfig, info, shouldCheckStack, true) + info, err = ProcessStacks(atmosConfig, info, shouldCheckStack, true) if err != nil { return err } @@ -97,22 +97,22 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { } if !info.ComponentIsEnabled { - u.LogInfo(cliConfig, fmt.Sprintf("component '%s' is not enabled and skipped", info.ComponentFromArg)) + u.LogInfo(atmosConfig, fmt.Sprintf("component '%s' is not enabled and skipped", info.ComponentFromArg)) return nil } - err = checkTerraformConfig(cliConfig) + err = checkTerraformConfig(atmosConfig) if err != nil { return err } // Check if the component (or base component) exists as Terraform component - componentPath := filepath.Join(cliConfig.TerraformDirAbsolutePath, info.ComponentFolderPrefix, info.FinalComponent) + componentPath := filepath.Join(atmosConfig.TerraformDirAbsolutePath, info.ComponentFolderPrefix, info.FinalComponent) componentPathExists, err := u.IsDirectory(componentPath) if err != nil || !componentPathExists { return fmt.Errorf("'%s' points to the Terraform component '%s', but it does not exist in '%s'", info.ComponentFromArg, info.FinalComponent, - filepath.Join(cliConfig.Components.Terraform.BasePath, info.ComponentFolderPrefix), + filepath.Join(atmosConfig.Components.Terraform.BasePath, info.ComponentFolderPrefix), ) } @@ -123,9 +123,9 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { } if info.SubCommand == "clean" { - err := handleCleanSubCommand(info, componentPath, cliConfig) + err := handleCleanSubCommand(info, componentPath, atmosConfig) if err != nil { - u.LogTrace(cliConfig, fmt.Errorf("error cleaning the terraform component: %v", err).Error()) + u.LogTrace(atmosConfig, fmt.Errorf("error cleaning the terraform component: %v", err).Error()) return err } return nil @@ -137,10 +137,10 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { // Print component variables and write to file // Don't process variables when executing `terraform workspace` commands if info.SubCommand != "workspace" { - u.LogDebug(cliConfig, fmt.Sprintf("\nVariables for the component '%s' in the stack '%s':", info.ComponentFromArg, info.Stack)) + u.LogDebug(atmosConfig, fmt.Sprintf("\nVariables for the component '%s' in the stack '%s':", info.ComponentFromArg, info.Stack)) - if cliConfig.Logs.Level == u.LogLevelTrace || cliConfig.Logs.Level == u.LogLevelDebug { - err = u.PrintAsYAMLToFileDescriptor(cliConfig, info.ComponentVarsSection) + if atmosConfig.Logs.Level == u.LogLevelTrace || atmosConfig.Logs.Level == u.LogLevelDebug { + err = u.PrintAsYAMLToFileDescriptor(atmosConfig, info.ComponentVarsSection) if err != nil { return err } @@ -163,11 +163,11 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { if len(varFileNameFromArg) > 0 { varFilePath = varFileNameFromArg } else { - varFilePath = constructTerraformComponentVarfilePath(cliConfig, info) + varFilePath = constructTerraformComponentVarfilePath(atmosConfig, info) } - u.LogDebug(cliConfig, "Writing the variables to file:") - u.LogDebug(cliConfig, varFilePath) + u.LogDebug(atmosConfig, "Writing the variables to file:") + u.LogDebug(atmosConfig, varFilePath) if !info.DryRun { err = u.WriteToFileAsJSON(varFilePath, info.ComponentVarsSection, 0644) @@ -184,7 +184,7 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { } // Check if component 'settings.validation' section is specified and validate the component - valid, err := ValidateComponent(cliConfig, info.ComponentFromArg, info.ComponentSection, "", "", nil, 0) + valid, err := ValidateComponent(atmosConfig, info.ComponentFromArg, info.ComponentSection, "", "", nil, 0) if err != nil { return err } @@ -193,14 +193,14 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { } // Component working directory - workingDir := constructTerraformComponentWorkingDir(cliConfig, info) + workingDir := constructTerraformComponentWorkingDir(atmosConfig, info) // Auto-generate backend file - if cliConfig.Components.Terraform.AutoGenerateBackendFile { + if atmosConfig.Components.Terraform.AutoGenerateBackendFile { backendFileName := filepath.Join(workingDir, "backend.tf.json") - u.LogDebug(cliConfig, "\nWriting the backend config to file:") - u.LogDebug(cliConfig, backendFileName) + u.LogDebug(atmosConfig, "\nWriting the backend config to file:") + u.LogDebug(atmosConfig, backendFileName) if !info.DryRun { componentBackendConfig, err := generateComponentBackendConfig(info.ComponentBackendType, info.ComponentBackendSection, info.TerraformWorkspace) @@ -219,8 +219,8 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { if len(info.ComponentProvidersSection) > 0 { providerOverrideFileName := filepath.Join(workingDir, "providers_override.tf.json") - u.LogDebug(cliConfig, "\nWriting the provider overrides to file:") - u.LogDebug(cliConfig, providerOverrideFileName) + u.LogDebug(atmosConfig, "\nWriting the provider overrides to file:") + u.LogDebug(atmosConfig, providerOverrideFileName) if !info.DryRun { var providerOverrides = generateComponentProviderOverrides(info.ComponentProvidersSection) @@ -237,7 +237,7 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { // Set 'TF_APPEND_USER_AGENT' ENV var based on precedence // Precedence: Environment Variable > atmos.yaml > Default - appendUserAgent := cliConfig.Components.Terraform.AppendUserAgent + appendUserAgent := atmosConfig.Components.Terraform.AppendUserAgent if envUA, exists := os.LookupEnv("TF_APPEND_USER_AGENT"); exists && envUA != "" { appendUserAgent = envUA } @@ -247,9 +247,9 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { // Print ENV vars if they are found in the component's stack config if len(info.ComponentEnvList) > 0 { - u.LogDebug(cliConfig, "\nUsing ENV vars:") + u.LogDebug(atmosConfig, "\nUsing ENV vars:") for _, v := range info.ComponentEnvList { - u.LogDebug(cliConfig, v) + u.LogDebug(atmosConfig, v) } } @@ -257,26 +257,26 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { runTerraformInit := true if info.SubCommand == "init" || info.SubCommand == "clean" || - (info.SubCommand == "deploy" && !cliConfig.Components.Terraform.DeployRunInit) { + (info.SubCommand == "deploy" && !atmosConfig.Components.Terraform.DeployRunInit) { runTerraformInit = false } if info.SkipInit { - u.LogDebug(cliConfig, "Skipping over 'terraform init' due to '--skip-init' flag being passed") + u.LogDebug(atmosConfig, "Skipping over 'terraform init' due to '--skip-init' flag being passed") runTerraformInit = false } if runTerraformInit { initCommandWithArguments := []string{"init"} - if info.SubCommand == "workspace" || cliConfig.Components.Terraform.InitRunReconfigure { + if info.SubCommand == "workspace" || atmosConfig.Components.Terraform.InitRunReconfigure { initCommandWithArguments = []string{"init", "-reconfigure"} } // Before executing `terraform init`, delete the `.terraform/environment` file from the component directory - cleanTerraformWorkspace(cliConfig, componentPath) + cleanTerraformWorkspace(atmosConfig, componentPath) err = ExecuteShellCommand( - cliConfig, + atmosConfig, info.Command, initCommandWithArguments, componentPath, @@ -297,42 +297,42 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { } } - // Handle cliConfig.Components.Terraform.ApplyAutoApprove flag - if info.SubCommand == "apply" && cliConfig.Components.Terraform.ApplyAutoApprove && !info.UseTerraformPlan { + // Handle atmosConfig.Components.Terraform.ApplyAutoApprove flag + if info.SubCommand == "apply" && atmosConfig.Components.Terraform.ApplyAutoApprove && !info.UseTerraformPlan { if !u.SliceContainsString(info.AdditionalArgsAndFlags, autoApproveFlag) { info.AdditionalArgsAndFlags = append(info.AdditionalArgsAndFlags, autoApproveFlag) } } // Print command info - u.LogDebug(cliConfig, "\nCommand info:") - u.LogDebug(cliConfig, "Terraform binary: "+info.Command) + u.LogDebug(atmosConfig, "\nCommand info:") + u.LogDebug(atmosConfig, "Terraform binary: "+info.Command) if info.SubCommand2 == "" { - u.LogDebug(cliConfig, fmt.Sprintf("Terraform command: %s", info.SubCommand)) + u.LogDebug(atmosConfig, fmt.Sprintf("Terraform command: %s", info.SubCommand)) } else { - u.LogDebug(cliConfig, fmt.Sprintf("Terraform command: %s %s", info.SubCommand, info.SubCommand2)) + u.LogDebug(atmosConfig, fmt.Sprintf("Terraform command: %s %s", info.SubCommand, info.SubCommand2)) } - u.LogDebug(cliConfig, fmt.Sprintf("Arguments and flags: %v", info.AdditionalArgsAndFlags)) - u.LogDebug(cliConfig, "Component: "+info.ComponentFromArg) + u.LogDebug(atmosConfig, fmt.Sprintf("Arguments and flags: %v", info.AdditionalArgsAndFlags)) + u.LogDebug(atmosConfig, "Component: "+info.ComponentFromArg) if len(info.BaseComponentPath) > 0 { - u.LogDebug(cliConfig, "Terraform component: "+info.BaseComponentPath) + u.LogDebug(atmosConfig, "Terraform component: "+info.BaseComponentPath) } if len(info.ComponentInheritanceChain) > 0 { - u.LogDebug(cliConfig, "Inheritance: "+info.ComponentFromArg+" -> "+strings.Join(info.ComponentInheritanceChain, " -> ")) + u.LogDebug(atmosConfig, "Inheritance: "+info.ComponentFromArg+" -> "+strings.Join(info.ComponentInheritanceChain, " -> ")) } if info.Stack == info.StackFromArg { - u.LogDebug(cliConfig, "Stack: "+info.StackFromArg) + u.LogDebug(atmosConfig, "Stack: "+info.StackFromArg) } else { - u.LogDebug(cliConfig, "Stack: "+info.StackFromArg) - u.LogDebug(cliConfig, "Stack path: "+filepath.Join(cliConfig.BasePath, cliConfig.Stacks.BasePath, info.Stack)) + u.LogDebug(atmosConfig, "Stack: "+info.StackFromArg) + u.LogDebug(atmosConfig, "Stack path: "+filepath.Join(atmosConfig.BasePath, atmosConfig.Stacks.BasePath, info.Stack)) } - u.LogDebug(cliConfig, fmt.Sprintf("Working dir: %s", workingDir)) + u.LogDebug(atmosConfig, fmt.Sprintf("Working dir: %s", workingDir)) allArgsAndFlags := strings.Fields(info.SubCommand) @@ -357,9 +357,9 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { } case "init": // Before executing `terraform init`, delete the `.terraform/environment` file from the component directory - cleanTerraformWorkspace(cliConfig, componentPath) + cleanTerraformWorkspace(atmosConfig, componentPath) - if cliConfig.Components.Terraform.InitRunReconfigure { + if atmosConfig.Components.Terraform.InitRunReconfigure { allArgsAndFlags = append(allArgsAndFlags, []string{"-reconfigure"}...) } case "workspace": @@ -399,7 +399,7 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { } err = ExecuteShellCommand( - cliConfig, + atmosConfig, info.Command, []string{"workspace", "select", info.TerraformWorkspace}, componentPath, @@ -415,7 +415,7 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { return err } err = ExecuteShellCommand( - cliConfig, + atmosConfig, info.Command, []string{"workspace", "new", info.TerraformWorkspace}, componentPath, @@ -455,7 +455,7 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { // Execute `terraform shell` command if info.SubCommand == "shell" { err = execTerraformShellCommand( - cliConfig, + atmosConfig, info.ComponentFromArg, info.Stack, info.ComponentEnvList, @@ -473,7 +473,7 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { // Execute the provided command (except for `terraform workspace` which was executed above) if !(info.SubCommand == "workspace" && info.SubCommand2 == "") { err = ExecuteShellCommand( - cliConfig, + atmosConfig, info.Command, allArgsAndFlags, componentPath, @@ -488,12 +488,12 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { // Clean up if info.SubCommand != "plan" && info.SubCommand != "show" && info.PlanFile == "" { - planFilePath := constructTerraformComponentPlanfilePath(cliConfig, info) + planFilePath := constructTerraformComponentPlanfilePath(atmosConfig, info) _ = os.Remove(planFilePath) } if info.SubCommand == "apply" { - varFilePath := constructTerraformComponentVarfilePath(cliConfig, info) + varFilePath := constructTerraformComponentVarfilePath(atmosConfig, info) _ = os.Remove(varFilePath) } diff --git a/internal/exec/terraform_clean.go b/internal/exec/terraform_clean.go index f77cbc98e..e3b190e01 100644 --- a/internal/exec/terraform_clean.go +++ b/internal/exec/terraform_clean.go @@ -28,7 +28,7 @@ type Directory struct { // findFoldersNamesWithPrefix finds the names of folders that match the given prefix under the specified root path. // The search is performed at the root level (level 1) and one level deeper (level 2). -func findFoldersNamesWithPrefix(root, prefix string, cliConfig schema.CliConfiguration) ([]string, error) { +func findFoldersNamesWithPrefix(root, prefix string, atmosConfig schema.AtmosConfiguration) ([]string, error) { var folderNames []string if root == "" { return nil, fmt.Errorf("root path cannot be empty") @@ -50,7 +50,7 @@ func findFoldersNamesWithPrefix(root, prefix string, cliConfig schema.CliConfigu level2Path := filepath.Join(root, dir.Name()) level2Dirs, err := os.ReadDir(level2Path) if err != nil { - u.LogWarning(cliConfig, fmt.Sprintf("Error reading subdirectory %s: %v", level2Path, err)) + u.LogWarning(atmosConfig, fmt.Sprintf("Error reading subdirectory %s: %v", level2Path, err)) continue } @@ -179,9 +179,9 @@ func CollectDirectoryObjects(basePath string, patterns []string) ([]Directory, e } // get stack terraform state files -func getStackTerraformStateFolder(componentPath string, stack string, cliConfig schema.CliConfiguration) ([]Directory, error) { +func getStackTerraformStateFolder(componentPath string, stack string, atmosConfig schema.AtmosConfiguration) ([]Directory, error) { tfStateFolderPath := filepath.Join(componentPath, "terraform.tfstate.d") - tfStateFolderNames, err := findFoldersNamesWithPrefix(tfStateFolderPath, stack, cliConfig) + tfStateFolderNames, err := findFoldersNamesWithPrefix(tfStateFolderPath, stack, atmosConfig) if err != nil { return nil, fmt.Errorf("failed to find stack folders: %w", err) } @@ -279,21 +279,21 @@ func DeletePathTerraform(fullPath string, objectName string) error { } // confirmDeletion prompts the user for confirmation before deletion. -func confirmDeletion(cliConfig schema.CliConfiguration) (bool, error) { +func confirmDeletion(atmosConfig schema.AtmosConfiguration) (bool, error) { message := "Are you sure?" confirm, err := confirmDeleteTerraformLocal(message) if err != nil { return false, err } if !confirm { - u.LogWarning(cliConfig, "Mission aborted.") + u.LogWarning(atmosConfig, "Mission aborted.") return false, nil } return true, nil } // deleteFolders handles the deletion of the specified folders and files. -func deleteFolders(folders []Directory, relativePath string, cliConfig schema.CliConfiguration) { +func deleteFolders(folders []Directory, relativePath string, atmosConfig schema.AtmosConfiguration) { var errors []error for _, folder := range folders { for _, file := range folder.Files { @@ -311,7 +311,7 @@ func deleteFolders(folders []Directory, relativePath string, cliConfig schema.Cl } if len(errors) > 0 { for _, err := range errors { - u.LogWarning(cliConfig, err.Error()) + u.LogWarning(atmosConfig, err.Error()) } } // check if the folder is empty by using the os.ReadDir function @@ -319,7 +319,7 @@ func deleteFolders(folders []Directory, relativePath string, cliConfig schema.Cl entries, err := os.ReadDir(folder.FullPath) if err == nil && len(entries) == 0 { if err := os.Remove(folder.FullPath); err != nil { - u.LogWarning(cliConfig, fmt.Sprintf("Error removing directory %s: %v", folder.FullPath, err)) + u.LogWarning(atmosConfig, fmt.Sprintf("Error removing directory %s: %v", folder.FullPath, err)) } } } @@ -327,26 +327,26 @@ func deleteFolders(folders []Directory, relativePath string, cliConfig schema.Cl } // handleTFDataDir handles the deletion of the TF_DATA_DIR if specified. -func handleTFDataDir(componentPath string, relativePath string, cliConfig schema.CliConfiguration) { +func handleTFDataDir(componentPath string, relativePath string, atmosConfig schema.AtmosConfiguration) { tfDataDir := os.Getenv("TF_DATA_DIR") if tfDataDir == "" { return } if err := IsValidDataDir(tfDataDir); err != nil { - u.LogWarning(cliConfig, err.Error()) + u.LogWarning(atmosConfig, err.Error()) return } if _, err := os.Stat(filepath.Join(componentPath, tfDataDir)); os.IsNotExist(err) { - u.LogWarning(cliConfig, fmt.Sprintf("TF_DATA_DIR '%s' does not exist", tfDataDir)) + u.LogWarning(atmosConfig, fmt.Sprintf("TF_DATA_DIR '%s' does not exist", tfDataDir)) return } if err := DeletePathTerraform(filepath.Join(componentPath, tfDataDir), filepath.Join(relativePath, tfDataDir)); err != nil { - u.LogWarning(cliConfig, err.Error()) + u.LogWarning(atmosConfig, err.Error()) } } -func initializeFilesToClear(info schema.ConfigAndStacksInfo, cliConfig schema.CliConfiguration, everything bool) []string { +func initializeFilesToClear(info schema.ConfigAndStacksInfo, atmosConfig schema.AtmosConfiguration, everything bool) []string { if everything && info.Stack == "" { return []string{".terraform", ".terraform.lock.hcl", "*.tfvar.json", "terraform.tfstate.d"} } @@ -358,7 +358,7 @@ func initializeFilesToClear(info schema.ConfigAndStacksInfo, cliConfig schema.Cl files = append(files, ".terraform.lock.hcl") } - if cliConfig.Components.Terraform.AutoGenerateBackendFile { + if atmosConfig.Components.Terraform.AutoGenerateBackendFile { files = append(files, "backend.tf.json") } @@ -382,7 +382,7 @@ func IsValidDataDir(tfDataDir string) error { } // handleCleanSubCommand handles the 'clean' subcommand logic. -func handleCleanSubCommand(info schema.ConfigAndStacksInfo, componentPath string, cliConfig schema.CliConfiguration) error { +func handleCleanSubCommand(info schema.ConfigAndStacksInfo, componentPath string, atmosConfig schema.AtmosConfiguration) error { if info.SubCommand != "clean" { return nil } @@ -394,7 +394,7 @@ func handleCleanSubCommand(info schema.ConfigAndStacksInfo, componentPath string cleanPath = filepath.Join(componentPath, info.Context.BaseComponent) } - relativePath, err := getRelativePath(cliConfig.BasePath, componentPath) + relativePath, err := getRelativePath(atmosConfig.BasePath, componentPath) if err != nil { return err } @@ -407,18 +407,18 @@ func handleCleanSubCommand(info schema.ConfigAndStacksInfo, componentPath string force := u.SliceContainsString(info.AdditionalArgsAndFlags, forceFlag) everything := u.SliceContainsString(info.AdditionalArgsAndFlags, everythingFlag) - filesToClear := initializeFilesToClear(info, cliConfig, everything) + filesToClear := initializeFilesToClear(info, atmosConfig, everything) folders, err := CollectDirectoryObjects(cleanPath, filesToClear) if err != nil { - u.LogTrace(cliConfig, fmt.Errorf("error collecting folders and files: %v", err).Error()) + u.LogTrace(atmosConfig, fmt.Errorf("error collecting folders and files: %v", err).Error()) return err } if info.Component != "" && info.Stack != "" { - stackFolders, err := getStackTerraformStateFolder(cleanPath, info.Stack, cliConfig) + stackFolders, err := getStackTerraformStateFolder(cleanPath, info.Stack, atmosConfig) if err != nil { errMsg := fmt.Errorf("error getting stack terraform state folders: %v", err) - u.LogTrace(cliConfig, errMsg.Error()) + u.LogTrace(atmosConfig, errMsg.Error()) } if stackFolders != nil { folders = append(folders, stackFolders...) @@ -429,11 +429,11 @@ func handleCleanSubCommand(info schema.ConfigAndStacksInfo, componentPath string var tfDataDirFolders []Directory if tfDataDir != "" { if err := IsValidDataDir(tfDataDir); err != nil { - u.LogTrace(cliConfig, err.Error()) + u.LogTrace(atmosConfig, err.Error()) } else { tfDataDirFolders, err = CollectDirectoryObjects(cleanPath, []string{tfDataDir}) if err != nil { - u.LogTrace(cliConfig, fmt.Errorf("error collecting folder of ENV TF_DATA_DIR: %v", err).Error()) + u.LogTrace(atmosConfig, fmt.Errorf("error collecting folder of ENV TF_DATA_DIR: %v", err).Error()) } } } @@ -466,15 +466,15 @@ func handleCleanSubCommand(info schema.ConfigAndStacksInfo, componentPath string } u.PrintMessage(message) println() - if confirm, err := confirmDeletion(cliConfig); err != nil || !confirm { + if confirm, err := confirmDeletion(atmosConfig); err != nil || !confirm { return err } } - deleteFolders(folders, relativePath, cliConfig) + deleteFolders(folders, relativePath, atmosConfig) if len(tfDataDirFolders) > 0 { tfDataDirFolder := tfDataDirFolders[0] - handleTFDataDir(tfDataDirFolder.FullPath, relativePath, cliConfig) + handleTFDataDir(tfDataDirFolder.FullPath, relativePath, atmosConfig) } } diff --git a/internal/exec/terraform_generate_backend.go b/internal/exec/terraform_generate_backend.go index 895ba26f7..632b8e508 100644 --- a/internal/exec/terraform_generate_backend.go +++ b/internal/exec/terraform_generate_backend.go @@ -35,12 +35,12 @@ func ExecuteTerraformGenerateBackendCmd(cmd *cobra.Command, args []string) error info.Stack = stack info.ComponentType = "terraform" - cliConfig, err := cfg.InitCliConfig(info, true) + atmosConfig, err := cfg.InitCliConfig(info, true) if err != nil { return err } - info, err = ProcessStacks(cliConfig, info, true, true) + info, err = ProcessStacks(atmosConfig, info, true, true) if err != nil { return err } @@ -58,10 +58,10 @@ func ExecuteTerraformGenerateBackendCmd(cmd *cobra.Command, args []string) error return err } - u.LogDebug(cliConfig, "Component backend config:\n\n") + u.LogDebug(atmosConfig, "Component backend config:\n\n") - if cliConfig.Logs.Level == u.LogLevelTrace || cliConfig.Logs.Level == u.LogLevelDebug { - err = u.PrintAsJSONToFileDescriptor(cliConfig, componentBackendConfig) + if atmosConfig.Logs.Level == u.LogLevelTrace || atmosConfig.Logs.Level == u.LogLevelDebug { + err = u.PrintAsJSONToFileDescriptor(atmosConfig, componentBackendConfig) if err != nil { return err } @@ -76,15 +76,15 @@ func ExecuteTerraformGenerateBackendCmd(cmd *cobra.Command, args []string) error // Write backend config to file var backendFilePath = filepath.Join( - cliConfig.BasePath, - cliConfig.Components.Terraform.BasePath, + atmosConfig.BasePath, + atmosConfig.Components.Terraform.BasePath, info.ComponentFolderPrefix, info.FinalComponent, "backend.tf.json", ) - u.LogDebug(cliConfig, "\nWriting the backend config to file:") - u.LogDebug(cliConfig, backendFilePath) + u.LogDebug(atmosConfig, "\nWriting the backend config to file:") + u.LogDebug(atmosConfig, backendFilePath) if !info.DryRun { err = u.WriteToFileAsJSON(backendFilePath, componentBackendConfig, 0644) diff --git a/internal/exec/terraform_generate_backends.go b/internal/exec/terraform_generate_backends.go index 1673a731b..9c2d32d58 100644 --- a/internal/exec/terraform_generate_backends.go +++ b/internal/exec/terraform_generate_backends.go @@ -21,7 +21,7 @@ func ExecuteTerraformGenerateBackendsCmd(cmd *cobra.Command, args []string) erro return err } - cliConfig, err := cfg.InitCliConfig(info, true) + atmosConfig, err := cfg.InitCliConfig(info, true) if err != nil { return err } @@ -62,18 +62,18 @@ func ExecuteTerraformGenerateBackendsCmd(cmd *cobra.Command, args []string) erro format = "hcl" } - return ExecuteTerraformGenerateBackends(cliConfig, fileTemplate, format, stacks, components) + return ExecuteTerraformGenerateBackends(atmosConfig, fileTemplate, format, stacks, components) } // ExecuteTerraformGenerateBackends generates backend configs for all terraform components func ExecuteTerraformGenerateBackends( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, fileTemplate string, format string, stacks []string, components []string, ) error { - stacksMap, _, err := FindStacksMap(cliConfig, false) + stacksMap, _, err := FindStacksMap(atmosConfig, false) if err != nil { return err } @@ -161,8 +161,8 @@ func ExecuteTerraformGenerateBackends( // Path to the terraform component terraformComponentPath := filepath.Join( - cliConfig.BasePath, - cliConfig.Components.Terraform.BasePath, + atmosConfig.BasePath, + atmosConfig.Components.Terraform.BasePath, terraformComponent, ) @@ -199,13 +199,13 @@ func ExecuteTerraformGenerateBackends( // Stack name var stackName string - if cliConfig.Stacks.NameTemplate != "" { - stackName, err = ProcessTmpl("terraform-generate-backends-template", cliConfig.Stacks.NameTemplate, configAndStacksInfo.ComponentSection, false) + if atmosConfig.Stacks.NameTemplate != "" { + stackName, err = ProcessTmpl("terraform-generate-backends-template", atmosConfig.Stacks.NameTemplate, configAndStacksInfo.ComponentSection, false) if err != nil { return err } } else { - stackName, err = cfg.GetContextPrefix(stackFileName, context, GetStackNamePattern(cliConfig), stackFileName) + stackName, err = cfg.GetContextPrefix(stackFileName, context, GetStackNamePattern(atmosConfig), stackFileName) if err != nil { return err } @@ -230,7 +230,7 @@ func ExecuteTerraformGenerateBackends( } componentSectionProcessed, err := ProcessTmplWithDatasources( - cliConfig, + atmosConfig, settingsSectionStruct, "terraform-generate-backends", componentSectionStr, @@ -243,17 +243,17 @@ func ExecuteTerraformGenerateBackends( componentSectionConverted, err := u.UnmarshalYAML[schema.AtmosSectionMapType](componentSectionProcessed) if err != nil { - if !cliConfig.Templates.Settings.Enabled { + if !atmosConfig.Templates.Settings.Enabled { if strings.Contains(componentSectionStr, "{{") || strings.Contains(componentSectionStr, "}}") { errorMessage := "the stack manifests contain Go templates, but templating is disabled in atmos.yaml in 'templates.settings.enabled'\n" + "to enable templating, refer to https://atmos.tools/core-concepts/stacks/templating" err = errors.Join(err, errors.New(errorMessage)) } } - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } - componentSectionFinal, err := ProcessCustomYamlTags(cliConfig, componentSectionConverted, stackName) + componentSectionFinal, err := ProcessCustomYamlTags(atmosConfig, componentSectionConverted, stackName) if err != nil { return err } @@ -320,7 +320,7 @@ func ExecuteTerraformGenerateBackends( } // Write the backend config to the file - u.LogDebug(cliConfig, fmt.Sprintf("Writing backend config for the component '%s' to file '%s'", terraformComponent, backendFilePath)) + u.LogDebug(atmosConfig, fmt.Sprintf("Writing backend config for the component '%s' to file '%s'", terraformComponent, backendFilePath)) if format == "json" { componentBackendConfig, err := generateComponentBackendConfig(backendTypeSection, backendSection, "") @@ -333,12 +333,12 @@ func ExecuteTerraformGenerateBackends( return err } } else if format == "hcl" { - err = u.WriteTerraformBackendConfigToFileAsHcl(cliConfig, backendFileAbsolutePath, backendTypeSection, backendSection) + err = u.WriteTerraformBackendConfigToFileAsHcl(atmosConfig, backendFileAbsolutePath, backendTypeSection, backendSection) if err != nil { return err } } else if format == "backend-config" { - err = u.WriteToFileAsHcl(cliConfig, backendFileAbsolutePath, backendSection, 0644) + err = u.WriteToFileAsHcl(atmosConfig, backendFileAbsolutePath, backendSection, 0644) if err != nil { return err } diff --git a/internal/exec/terraform_generate_varfile.go b/internal/exec/terraform_generate_varfile.go index 6ef9f8740..6bc8263f6 100644 --- a/internal/exec/terraform_generate_varfile.go +++ b/internal/exec/terraform_generate_varfile.go @@ -34,12 +34,12 @@ func ExecuteTerraformGenerateVarfileCmd(cmd *cobra.Command, args []string) error info.Stack = stack info.ComponentType = "terraform" - cliConfig, err := cfg.InitCliConfig(info, true) + atmosConfig, err := cfg.InitCliConfig(info, true) if err != nil { return err } - info, err = ProcessStacks(cliConfig, info, true, true) + info, err = ProcessStacks(atmosConfig, info, true, true) if err != nil { return err } @@ -55,22 +55,22 @@ func ExecuteTerraformGenerateVarfileCmd(cmd *cobra.Command, args []string) error if len(varFileNameFromArg) > 0 { varFilePath = varFileNameFromArg } else { - varFilePath = constructTerraformComponentVarfilePath(cliConfig, info) + varFilePath = constructTerraformComponentVarfilePath(atmosConfig, info) } // Print the component variables - u.LogDebug(cliConfig, fmt.Sprintf("\nVariables for the component '%s' in the stack '%s':", info.ComponentFromArg, info.Stack)) + u.LogDebug(atmosConfig, fmt.Sprintf("\nVariables for the component '%s' in the stack '%s':", info.ComponentFromArg, info.Stack)) - if cliConfig.Logs.Level == u.LogLevelTrace || cliConfig.Logs.Level == u.LogLevelDebug { - err = u.PrintAsYAMLToFileDescriptor(cliConfig, info.ComponentVarsSection) + if atmosConfig.Logs.Level == u.LogLevelTrace || atmosConfig.Logs.Level == u.LogLevelDebug { + err = u.PrintAsYAMLToFileDescriptor(atmosConfig, info.ComponentVarsSection) if err != nil { return err } } // Write the variables to file - u.LogDebug(cliConfig, "Writing the variables to file:") - u.LogDebug(cliConfig, varFilePath) + u.LogDebug(atmosConfig, "Writing the variables to file:") + u.LogDebug(atmosConfig, varFilePath) if !info.DryRun { err = u.WriteToFileAsJSON(varFilePath, info.ComponentVarsSection, 0644) diff --git a/internal/exec/terraform_generate_varfiles.go b/internal/exec/terraform_generate_varfiles.go index 9c50da888..04ef9466f 100644 --- a/internal/exec/terraform_generate_varfiles.go +++ b/internal/exec/terraform_generate_varfiles.go @@ -21,7 +21,7 @@ func ExecuteTerraformGenerateVarfilesCmd(cmd *cobra.Command, args []string) erro return err } - cliConfig, err := cfg.InitCliConfig(info, true) + atmosConfig, err := cfg.InitCliConfig(info, true) if err != nil { return err } @@ -62,18 +62,18 @@ func ExecuteTerraformGenerateVarfilesCmd(cmd *cobra.Command, args []string) erro format = "json" } - return ExecuteTerraformGenerateVarfiles(cliConfig, fileTemplate, format, stacks, components) + return ExecuteTerraformGenerateVarfiles(atmosConfig, fileTemplate, format, stacks, components) } // ExecuteTerraformGenerateVarfiles generates varfiles for all terraform components in all stacks func ExecuteTerraformGenerateVarfiles( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, fileTemplate string, format string, stacks []string, components []string, ) error { - stacksMap, _, err := FindStacksMap(cliConfig, false) + stacksMap, _, err := FindStacksMap(atmosConfig, false) if err != nil { return err } @@ -160,8 +160,8 @@ func ExecuteTerraformGenerateVarfiles( // Absolute path to the terraform component terraformComponentPath := filepath.Join( - cliConfig.BasePath, - cliConfig.Components.Terraform.BasePath, + atmosConfig.BasePath, + atmosConfig.Components.Terraform.BasePath, terraformComponent, ) @@ -198,13 +198,13 @@ func ExecuteTerraformGenerateVarfiles( // Stack name var stackName string - if cliConfig.Stacks.NameTemplate != "" { - stackName, err = ProcessTmpl("terraform-generate-varfiles-template", cliConfig.Stacks.NameTemplate, configAndStacksInfo.ComponentSection, false) + if atmosConfig.Stacks.NameTemplate != "" { + stackName, err = ProcessTmpl("terraform-generate-varfiles-template", atmosConfig.Stacks.NameTemplate, configAndStacksInfo.ComponentSection, false) if err != nil { return err } } else { - stackName, err = cfg.GetContextPrefix(stackFileName, context, GetStackNamePattern(cliConfig), stackFileName) + stackName, err = cfg.GetContextPrefix(stackFileName, context, GetStackNamePattern(atmosConfig), stackFileName) if err != nil { return err } @@ -219,7 +219,7 @@ func ExecuteTerraformGenerateVarfiles( configAndStacksInfo.ComponentSection["atmos_manifest"] = stackFileName // Terraform workspace - workspace, err := BuildTerraformWorkspace(cliConfig, configAndStacksInfo) + workspace, err := BuildTerraformWorkspace(atmosConfig, configAndStacksInfo) if err != nil { return err } @@ -246,7 +246,7 @@ func ExecuteTerraformGenerateVarfiles( } componentSectionProcessed, err := ProcessTmplWithDatasources( - cliConfig, + atmosConfig, settingsSectionStruct, "terraform-generate-varfiles", componentSectionStr, @@ -259,17 +259,17 @@ func ExecuteTerraformGenerateVarfiles( componentSectionConverted, err := u.UnmarshalYAML[schema.AtmosSectionMapType](componentSectionProcessed) if err != nil { - if !cliConfig.Templates.Settings.Enabled { + if !atmosConfig.Templates.Settings.Enabled { if strings.Contains(componentSectionStr, "{{") || strings.Contains(componentSectionStr, "}}") { errorMessage := "the stack manifests contain Go templates, but templating is disabled in atmos.yaml in 'templates.settings.enabled'\n" + "to enable templating, refer to https://atmos.tools/core-concepts/stacks/templating" err = errors.Join(err, errors.New(errorMessage)) } } - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } - componentSectionFinal, err := ProcessCustomYamlTags(cliConfig, componentSectionConverted, stackName) + componentSectionFinal, err := ProcessCustomYamlTags(atmosConfig, componentSectionConverted, stackName) if err != nil { return err } @@ -315,7 +315,7 @@ func ExecuteTerraformGenerateVarfiles( return err } } else if format == "hcl" { - err = u.WriteToFileAsHcl(cliConfig, fileAbsolutePath, varsSection, 0644) + err = u.WriteToFileAsHcl(atmosConfig, fileAbsolutePath, varsSection, 0644) if err != nil { return err } @@ -323,11 +323,11 @@ func ExecuteTerraformGenerateVarfiles( return fmt.Errorf("invalid '--format' argument '%s'. Valid values are 'json' (default), 'yaml' and 'hcl", format) } - u.LogDebug(cliConfig, fmt.Sprintf("varfile: %s", fileName)) - u.LogDebug(cliConfig, fmt.Sprintf("terraform component: %s", terraformComponent)) - u.LogDebug(cliConfig, fmt.Sprintf("atmos component: %s", componentName)) - u.LogDebug(cliConfig, fmt.Sprintf("atmos stack: %s", stackName)) - u.LogDebug(cliConfig, fmt.Sprintf("stack config file: %s", stackFileName)) + u.LogDebug(atmosConfig, fmt.Sprintf("varfile: %s", fileName)) + u.LogDebug(atmosConfig, fmt.Sprintf("terraform component: %s", terraformComponent)) + u.LogDebug(atmosConfig, fmt.Sprintf("atmos component: %s", componentName)) + u.LogDebug(atmosConfig, fmt.Sprintf("atmos stack: %s", stackName)) + u.LogDebug(atmosConfig, fmt.Sprintf("stack config file: %s", stackFileName)) } } } diff --git a/internal/exec/terraform_utils.go b/internal/exec/terraform_utils.go index 621c6122b..03e5a656c 100644 --- a/internal/exec/terraform_utils.go +++ b/internal/exec/terraform_utils.go @@ -16,8 +16,8 @@ import ( u "github.com/cloudposse/atmos/pkg/utils" ) -func checkTerraformConfig(cliConfig schema.CliConfiguration) error { - if len(cliConfig.Components.Terraform.BasePath) < 1 { +func checkTerraformConfig(atmosConfig schema.AtmosConfiguration) error { + if len(atmosConfig.Components.Terraform.BasePath) < 1 { return errors.New("Base path to terraform components must be provided in 'components.terraform.base_path' config or " + "'ATMOS_COMPONENTS_TERRAFORM_BASE_PATH' ENV variable") } @@ -30,13 +30,13 @@ func checkTerraformConfig(cliConfig schema.CliConfiguration) error { // helping Terraform identify the active workspace context for managing your infrastructure. // We delete the file to prevent the Terraform prompt asking to select the default or the // previously used workspace. This happens when different backends are used for the same component. -func cleanTerraformWorkspace(cliConfig schema.CliConfiguration, componentPath string) { +func cleanTerraformWorkspace(atmosConfig schema.AtmosConfiguration, componentPath string) { filePath := filepath.Join(componentPath, ".terraform", "environment") - u.LogDebug(cliConfig, fmt.Sprintf("\nDeleting Terraform environment file:\n'%s'", filePath)) + u.LogDebug(atmosConfig, fmt.Sprintf("\nDeleting Terraform environment file:\n'%s'", filePath)) _ = os.Remove(filePath) } -func execTerraformOutput(cliConfig schema.CliConfiguration, component string, stack string, sections map[string]any) (map[string]any, error) { +func execTerraformOutput(atmosConfig schema.AtmosConfiguration, component string, stack string, sections map[string]any) (map[string]any, error) { outputProcessed := map[string]any{} componentAbstract := false componentEnabled := true @@ -86,11 +86,11 @@ func execTerraformOutput(cliConfig schema.CliConfiguration, component string, st } // Auto-generate backend file - if cliConfig.Components.Terraform.AutoGenerateBackendFile { + if atmosConfig.Components.Terraform.AutoGenerateBackendFile { backendFileName := filepath.Join(componentPath, "backend.tf.json") - u.LogTrace(cliConfig, "\nWriting the backend config to file:") - u.LogTrace(cliConfig, backendFileName) + u.LogTrace(atmosConfig, "\nWriting the backend config to file:") + u.LogTrace(atmosConfig, backendFileName) backendTypeSection, ok := sections["backend_type"].(string) if !ok { @@ -112,8 +112,8 @@ func execTerraformOutput(cliConfig schema.CliConfiguration, component string, st return nil, err } - u.LogTrace(cliConfig, "\nWrote the backend config to file:") - u.LogTrace(cliConfig, backendFileName) + u.LogTrace(atmosConfig, "\nWrote the backend config to file:") + u.LogTrace(atmosConfig, backendFileName) } // Generate `providers_override.tf.json` file if the `providers` section is configured @@ -122,8 +122,8 @@ func execTerraformOutput(cliConfig schema.CliConfiguration, component string, st if ok && len(providersSection) > 0 { providerOverrideFileName := filepath.Join(componentPath, "providers_override.tf.json") - u.LogTrace(cliConfig, "\nWriting the provider overrides to file:") - u.LogTrace(cliConfig, providerOverrideFileName) + u.LogTrace(atmosConfig, "\nWriting the provider overrides to file:") + u.LogTrace(atmosConfig, providerOverrideFileName) var providerOverrides = generateComponentProviderOverrides(providersSection) err = u.WriteToFileAsJSON(providerOverrideFileName, providerOverrides, 0644) @@ -131,8 +131,8 @@ func execTerraformOutput(cliConfig schema.CliConfiguration, component string, st return nil, err } - u.LogTrace(cliConfig, "\nWrote the provider overrides to file:") - u.LogTrace(cliConfig, providerOverrideFileName) + u.LogTrace(atmosConfig, "\nWrote the provider overrides to file:") + u.LogTrace(atmosConfig, providerOverrideFileName) } // Initialize Terraform/OpenTofu @@ -146,57 +146,57 @@ func execTerraformOutput(cliConfig schema.CliConfiguration, component string, st // 'terraform init' // Before executing `terraform init`, delete the `.terraform/environment` file from the component directory - cleanTerraformWorkspace(cliConfig, componentPath) + cleanTerraformWorkspace(atmosConfig, componentPath) - u.LogTrace(cliConfig, fmt.Sprintf("\nExecuting 'terraform init %s -s %s'", component, stack)) + u.LogTrace(atmosConfig, fmt.Sprintf("\nExecuting 'terraform init %s -s %s'", component, stack)) err = tf.Init(ctx, tfexec.Upgrade(false)) if err != nil { return nil, err } - u.LogTrace(cliConfig, fmt.Sprintf("\nExecuted 'terraform init %s -s %s'", component, stack)) + u.LogTrace(atmosConfig, fmt.Sprintf("\nExecuted 'terraform init %s -s %s'", component, stack)) // Terraform workspace - u.LogTrace(cliConfig, fmt.Sprintf("\nExecuting 'terraform workspace new %s' for component '%s' in stack '%s'", terraformWorkspace, component, stack)) + u.LogTrace(atmosConfig, fmt.Sprintf("\nExecuting 'terraform workspace new %s' for component '%s' in stack '%s'", terraformWorkspace, component, stack)) err = tf.WorkspaceNew(ctx, terraformWorkspace) if err != nil { - u.LogTrace(cliConfig, fmt.Sprintf("\nWorkspace exists. Executing 'terraform workspace select %s' for component '%s' in stack '%s'", terraformWorkspace, component, stack)) + u.LogTrace(atmosConfig, fmt.Sprintf("\nWorkspace exists. Executing 'terraform workspace select %s' for component '%s' in stack '%s'", terraformWorkspace, component, stack)) err = tf.WorkspaceSelect(ctx, terraformWorkspace) if err != nil { return nil, err } - u.LogTrace(cliConfig, fmt.Sprintf("\nExecuted 'terraform workspace select %s' for component '%s' in stack '%s'", terraformWorkspace, component, stack)) + u.LogTrace(atmosConfig, fmt.Sprintf("\nExecuted 'terraform workspace select %s' for component '%s' in stack '%s'", terraformWorkspace, component, stack)) } else { - u.LogTrace(cliConfig, fmt.Sprintf("\nExecuted 'terraform workspace new %s' for component '%s' in stack '%s'", terraformWorkspace, component, stack)) + u.LogTrace(atmosConfig, fmt.Sprintf("\nExecuted 'terraform workspace new %s' for component '%s' in stack '%s'", terraformWorkspace, component, stack)) } // Terraform output - u.LogTrace(cliConfig, fmt.Sprintf("\nExecuting 'terraform output %s -s %s'", component, stack)) + u.LogTrace(atmosConfig, fmt.Sprintf("\nExecuting 'terraform output %s -s %s'", component, stack)) outputMeta, err := tf.Output(ctx) if err != nil { return nil, err } - u.LogTrace(cliConfig, fmt.Sprintf("\nExecuted 'terraform output %s -s %s'", component, stack)) + u.LogTrace(atmosConfig, fmt.Sprintf("\nExecuted 'terraform output %s -s %s'", component, stack)) - if cliConfig.Logs.Level == u.LogLevelTrace { + if atmosConfig.Logs.Level == u.LogLevelTrace { y, err2 := u.ConvertToYAML(outputMeta) if err2 != nil { - u.LogError(cliConfig, err2) + u.LogError(atmosConfig, err2) } else { - u.LogTrace(cliConfig, fmt.Sprintf("\nResult of 'terraform output %s -s %s' before processing it:\n%s\n", component, stack, y)) + u.LogTrace(atmosConfig, fmt.Sprintf("\nResult of 'terraform output %s -s %s' before processing it:\n%s\n", component, stack, y)) } } outputProcessed = lo.MapEntries(outputMeta, func(k string, v tfexec.OutputMeta) (string, any) { s := string(v.Value) - u.LogTrace(cliConfig, fmt.Sprintf("Converting the variable '%s' with the value\n%s\nfrom JSON to 'Go' data type\n", k, s)) + u.LogTrace(atmosConfig, fmt.Sprintf("Converting the variable '%s' with the value\n%s\nfrom JSON to 'Go' data type\n", k, s)) d, err2 := u.ConvertFromJSON(s) if err2 != nil { - u.LogError(cliConfig, fmt.Errorf("failed to convert output '%s': %w", k, err2)) + u.LogError(atmosConfig, fmt.Errorf("failed to convert output '%s': %w", k, err2)) return k, nil } else { - u.LogTrace(cliConfig, fmt.Sprintf("Converted the variable '%s' with the value\n%s\nfrom JSON to 'Go' data type\nResult: %v\n", k, s, d)) + u.LogTrace(atmosConfig, fmt.Sprintf("Converted the variable '%s' with the value\n%s\nfrom JSON to 'Go' data type\nResult: %v\n", k, s, d)) } return k, d @@ -206,7 +206,7 @@ func execTerraformOutput(cliConfig schema.CliConfiguration, component string, st if componentAbstract { componentType = "abstract" } - u.LogTrace(cliConfig, fmt.Sprintf("\nNot executing 'terraform output %s -s %s' because the component is %s", component, stack, componentType)) + u.LogTrace(atmosConfig, fmt.Sprintf("\nNot executing 'terraform output %s -s %s' because the component is %s", component, stack, componentType)) } return outputProcessed, nil diff --git a/internal/exec/utils.go b/internal/exec/utils.go index 32bf516af..a3a7c9cc5 100644 --- a/internal/exec/utils.go +++ b/internal/exec/utils.go @@ -226,7 +226,7 @@ func ProcessCommandLineArgs( if argsAndFlagsInfo.SubCommand == "-h" || argsAndFlagsInfo.SubCommand == "--help" { argsAndFlagsInfo.SubCommand = "" } - err = processHelp(schema.CliConfiguration{}, componentType, argsAndFlagsInfo.SubCommand) + err = processHelp(schema.AtmosConfiguration{}, componentType, argsAndFlagsInfo.SubCommand) if err != nil { return configAndStacksInfo, err } @@ -244,18 +244,18 @@ func ProcessCommandLineArgs( } // FindStacksMap processes stack config and returns a map of all stacks -func FindStacksMap(cliConfig schema.CliConfiguration, ignoreMissingFiles bool) ( +func FindStacksMap(atmosConfig schema.AtmosConfiguration, ignoreMissingFiles bool) ( map[string]any, map[string]map[string]any, error, ) { // Process stack config file(s) _, stacksMap, rawStackConfigs, err := ProcessYAMLConfigFiles( - cliConfig, - cliConfig.StacksBaseAbsolutePath, - cliConfig.TerraformDirAbsolutePath, - cliConfig.HelmfileDirAbsolutePath, - cliConfig.StackConfigFilesAbsolutePaths, + atmosConfig, + atmosConfig.StacksBaseAbsolutePath, + atmosConfig.TerraformDirAbsolutePath, + atmosConfig.HelmfileDirAbsolutePath, + atmosConfig.StackConfigFilesAbsolutePaths, false, true, ignoreMissingFiles, @@ -270,7 +270,7 @@ func FindStacksMap(cliConfig schema.CliConfiguration, ignoreMissingFiles bool) ( // ProcessStacks processes stack config func ProcessStacks( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, configAndStacksInfo schema.ConfigAndStacksInfo, checkStack bool, processTemplates bool, @@ -290,28 +290,28 @@ func ProcessStacks( configAndStacksInfo.StackFromArg = configAndStacksInfo.Stack - stacksMap, rawStackConfigs, err := FindStacksMap(cliConfig, false) + stacksMap, rawStackConfigs, err := FindStacksMap(atmosConfig, false) if err != nil { return configAndStacksInfo, err } // Print the stack config files - if cliConfig.Logs.Level == u.LogLevelTrace { + if atmosConfig.Logs.Level == u.LogLevelTrace { var msg string - if cliConfig.StackType == "Directory" { + if atmosConfig.StackType == "Directory" { msg = "\nFound stack manifest:" } else { msg = "\nFound stack manifests:" } - u.LogTrace(cliConfig, msg) - err = u.PrintAsYAMLToFileDescriptor(cliConfig, cliConfig.StackConfigFilesRelativePaths) + u.LogTrace(atmosConfig, msg) + err = u.PrintAsYAMLToFileDescriptor(atmosConfig, atmosConfig.StackConfigFilesRelativePaths) if err != nil { return configAndStacksInfo, err } } // Check and process stacks - if cliConfig.StackType == "Directory" { + if atmosConfig.StackType == "Directory" { err = ProcessComponentConfig( &configAndStacksInfo, configAndStacksInfo.Stack, @@ -332,7 +332,7 @@ func ProcessStacks( configAndStacksInfo.ContextPrefix, err = cfg.GetContextPrefix(configAndStacksInfo.Stack, configAndStacksInfo.Context, - GetStackNamePattern(cliConfig), + GetStackNamePattern(atmosConfig), configAndStacksInfo.Stack, ) if err != nil { @@ -356,19 +356,19 @@ func ProcessStacks( continue } - if cliConfig.Stacks.NameTemplate != "" { - tmpl, err2 := ProcessTmpl("name-template", cliConfig.Stacks.NameTemplate, configAndStacksInfo.ComponentSection, false) + if atmosConfig.Stacks.NameTemplate != "" { + tmpl, err2 := ProcessTmpl("name-template", atmosConfig.Stacks.NameTemplate, configAndStacksInfo.ComponentSection, false) if err2 != nil { continue } configAndStacksInfo.ContextPrefix = tmpl - } else if cliConfig.Stacks.NamePattern != "" { + } else if atmosConfig.Stacks.NamePattern != "" { // Process context configAndStacksInfo.Context = cfg.GetContextFromVars(configAndStacksInfo.ComponentVarsSection) configAndStacksInfo.ContextPrefix, err = cfg.GetContextPrefix(configAndStacksInfo.Stack, configAndStacksInfo.Context, - GetStackNamePattern(cliConfig), + GetStackNamePattern(atmosConfig), stackName, ) if err != nil { @@ -389,7 +389,7 @@ func ProcessStacks( foundStacks = append(foundStacks, stackName) u.LogDebug( - cliConfig, + atmosConfig, fmt.Sprintf("Found component '%s' in the stack '%s' in the stack manifest '%s'", configAndStacksInfo.ComponentFromArg, configAndStacksInfo.Stack, @@ -406,8 +406,8 @@ func ProcessStacks( if foundStackCount == 0 { cliConfigYaml := "" - if cliConfig.Logs.Level == u.LogLevelTrace { - y, _ := u.ConvertToYAML(cliConfig) + if atmosConfig.Logs.Level == u.LogLevelTrace { + y, _ := u.ConvertToYAML(atmosConfig) cliConfigYaml = fmt.Sprintf("\n\n\nCLI config: %v\n", y) } @@ -426,7 +426,7 @@ func ProcessStacks( configAndStacksInfo.Stack, strings.Join(foundStacks, ", "), ) - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } else { configAndStacksInfo = foundConfigAndStacksInfo } @@ -444,10 +444,10 @@ func ProcessStacks( // Add Atmos CLI config atmosCliConfig := map[string]any{} - atmosCliConfig["base_path"] = cliConfig.BasePath - atmosCliConfig["components"] = cliConfig.Components - atmosCliConfig["stacks"] = cliConfig.Stacks - atmosCliConfig["workflows"] = cliConfig.Workflows + atmosCliConfig["base_path"] = atmosConfig.BasePath + atmosCliConfig["components"] = atmosConfig.Components + atmosCliConfig["stacks"] = atmosConfig.Stacks + atmosCliConfig["workflows"] = atmosConfig.Workflows configAndStacksInfo.ComponentSection["atmos_cli_config"] = atmosCliConfig // If the command-line component does not inherit anything, then the Terraform/Helmfile component is the same as the provided one @@ -472,7 +472,7 @@ func ProcessStacks( configAndStacksInfo.ComponentSection["deps_all"] = componentDepsAll // Terraform workspace - workspace, err := BuildTerraformWorkspace(cliConfig, configAndStacksInfo) + workspace, err := BuildTerraformWorkspace(atmosConfig, configAndStacksInfo) if err != nil { return configAndStacksInfo, err } @@ -495,7 +495,7 @@ func ProcessStacks( } componentSectionProcessed, err := ProcessTmplWithDatasources( - cliConfig, + atmosConfig, settingsSectionStruct, "all-atmos-sections", componentSectionStr, @@ -504,22 +504,22 @@ func ProcessStacks( ) if err != nil { // If any error returned from the templates processing, log it and exit - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } componentSectionConverted, err := u.UnmarshalYAML[schema.AtmosSectionMapType](componentSectionProcessed) if err != nil { - if !cliConfig.Templates.Settings.Enabled { + if !atmosConfig.Templates.Settings.Enabled { if strings.Contains(componentSectionStr, "{{") || strings.Contains(componentSectionStr, "}}") { errorMessage := "the stack manifests contain Go templates, but templating is disabled in atmos.yaml in 'templates.settings.enabled'\n" + "to enable templating, refer to https://atmos.tools/core-concepts/stacks/templates" err = errors.Join(err, errors.New(errorMessage)) } } - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } - componentSectionFinal, err := ProcessCustomYamlTags(cliConfig, componentSectionConverted, configAndStacksInfo.Stack) + componentSectionFinal, err := ProcessCustomYamlTags(atmosConfig, componentSectionConverted, configAndStacksInfo.Stack) if err != nil { return configAndStacksInfo, err } @@ -573,7 +573,7 @@ func ProcessStacks( } // Spacelift stack - spaceliftStackName, err := BuildSpaceliftStackNameFromComponentConfig(cliConfig, configAndStacksInfo) + spaceliftStackName, err := BuildSpaceliftStackNameFromComponentConfig(atmosConfig, configAndStacksInfo) if err != nil { return configAndStacksInfo, err } @@ -582,7 +582,7 @@ func ProcessStacks( } // Atlantis project - atlantisProjectName, err := BuildAtlantisProjectNameFromComponentConfig(cliConfig, configAndStacksInfo) + atlantisProjectName, err := BuildAtlantisProjectNameFromComponentConfig(atmosConfig, configAndStacksInfo) if err != nil { return configAndStacksInfo, err } @@ -638,12 +638,12 @@ func ProcessStacks( componentInfo["component_type"] = configAndStacksInfo.ComponentType if configAndStacksInfo.ComponentType == "terraform" { - componentPath := constructTerraformComponentWorkingDir(cliConfig, configAndStacksInfo) + componentPath := constructTerraformComponentWorkingDir(atmosConfig, configAndStacksInfo) componentInfo["component_path"] = componentPath terraformConfiguration, _ := tfconfig.LoadModule(componentPath) componentInfo["terraform_config"] = terraformConfiguration } else if configAndStacksInfo.ComponentType == "helmfile" { - componentInfo["component_path"] = constructHelmfileComponentWorkingDir(cliConfig, configAndStacksInfo) + componentInfo["component_path"] = constructHelmfileComponentWorkingDir(atmosConfig, configAndStacksInfo) } configAndStacksInfo.ComponentSection["component_info"] = componentInfo diff --git a/internal/exec/validate_component.go b/internal/exec/validate_component.go index 3155cf98e..96875bc4c 100644 --- a/internal/exec/validate_component.go +++ b/internal/exec/validate_component.go @@ -21,7 +21,7 @@ func ExecuteValidateComponentCmd(cmd *cobra.Command, args []string) (string, str return "", "", err } - cliConfig, err := cfg.InitCliConfig(info, true) + atmosConfig, err := cfg.InitCliConfig(info, true) if err != nil { return "", "", err } @@ -59,7 +59,7 @@ func ExecuteValidateComponentCmd(cmd *cobra.Command, args []string) (string, str return "", "", err } - _, err = ExecuteValidateComponent(cliConfig, info, componentName, stack, schemaPath, schemaType, modulePaths, timeout) + _, err = ExecuteValidateComponent(atmosConfig, info, componentName, stack, schemaPath, schemaType, modulePaths, timeout) if err != nil { return "", "", err } @@ -69,7 +69,7 @@ func ExecuteValidateComponentCmd(cmd *cobra.Command, args []string) (string, str // ExecuteValidateComponent validates a component in a stack using JsonSchema, OPA or CUE schema documents func ExecuteValidateComponent( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, configAndStacksInfo schema.ConfigAndStacksInfo, componentName string, stack string, @@ -82,10 +82,10 @@ func ExecuteValidateComponent( configAndStacksInfo.Stack = stack configAndStacksInfo.ComponentType = "terraform" - configAndStacksInfo, err := ProcessStacks(cliConfig, configAndStacksInfo, true, true) + configAndStacksInfo, err := ProcessStacks(atmosConfig, configAndStacksInfo, true, true) if err != nil { configAndStacksInfo.ComponentType = "helmfile" - configAndStacksInfo, err = ProcessStacks(cliConfig, configAndStacksInfo, true, true) + configAndStacksInfo, err = ProcessStacks(atmosConfig, configAndStacksInfo, true, true) if err != nil { return false, err } @@ -93,12 +93,12 @@ func ExecuteValidateComponent( componentSection := configAndStacksInfo.ComponentSection - return ValidateComponent(cliConfig, componentName, componentSection, schemaPath, schemaType, modulePaths, timeoutSeconds) + return ValidateComponent(atmosConfig, componentName, componentSection, schemaPath, schemaType, modulePaths, timeoutSeconds) } // ValidateComponent validates the component config using JsonSchema, OPA or CUE schema documents func ValidateComponent( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, componentName string, componentSection any, schemaPath string, @@ -110,9 +110,9 @@ func ValidateComponent( var err error if schemaPath != "" && schemaType != "" { - u.LogDebug(cliConfig, fmt.Sprintf("\nValidating the component '%s' using '%s' file '%s'", componentName, schemaType, schemaPath)) + u.LogDebug(atmosConfig, fmt.Sprintf("\nValidating the component '%s' using '%s' file '%s'", componentName, schemaType, schemaPath)) - ok, err = validateComponentInternal(cliConfig, componentSection, schemaPath, schemaType, modulePaths, timeoutSeconds) + ok, err = validateComponentInternal(atmosConfig, componentSection, schemaPath, schemaType, modulePaths, timeoutSeconds) if err != nil { return false, err } @@ -157,13 +157,13 @@ func ValidateComponent( finalTimeoutSeconds = v.Timeout } - u.LogDebug(cliConfig, fmt.Sprintf("\nValidating the component '%s' using '%s' file '%s'", componentName, finalSchemaType, finalSchemaPath)) + u.LogDebug(atmosConfig, fmt.Sprintf("\nValidating the component '%s' using '%s' file '%s'", componentName, finalSchemaType, finalSchemaPath)) if v.Description != "" { - u.LogDebug(cliConfig, v.Description) + u.LogDebug(atmosConfig, v.Description) } - ok2, err := validateComponentInternal(cliConfig, componentSection, finalSchemaPath, finalSchemaType, finalModulePaths, finalTimeoutSeconds) + ok2, err := validateComponentInternal(atmosConfig, componentSection, finalSchemaPath, finalSchemaType, finalModulePaths, finalTimeoutSeconds) if err != nil { return false, err } @@ -177,7 +177,7 @@ func ValidateComponent( } func validateComponentInternal( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, componentSection any, schemaPath string, schemaType string, @@ -197,11 +197,11 @@ func validateComponentInternal( switch schemaType { case "jsonschema": { - filePath = filepath.Join(cliConfig.BasePath, cliConfig.Schemas.JsonSchema.BasePath, schemaPath) + filePath = filepath.Join(atmosConfig.BasePath, atmosConfig.Schemas.JsonSchema.BasePath, schemaPath) } case "opa": { - filePath = filepath.Join(cliConfig.BasePath, cliConfig.Schemas.Opa.BasePath, schemaPath) + filePath = filepath.Join(atmosConfig.BasePath, atmosConfig.Schemas.Opa.BasePath, schemaPath) } } @@ -228,7 +228,7 @@ func validateComponentInternal( } case "opa": { - modulePathsAbsolute, err := u.JoinAbsolutePathWithPaths(filepath.Join(cliConfig.BasePath, cliConfig.Schemas.Opa.BasePath), modulePaths) + modulePathsAbsolute, err := u.JoinAbsolutePathWithPaths(filepath.Join(atmosConfig.BasePath, atmosConfig.Schemas.Opa.BasePath), modulePaths) if err != nil { return false, err } diff --git a/internal/exec/validate_stacks.go b/internal/exec/validate_stacks.go index 8861f8c69..e272340e7 100644 --- a/internal/exec/validate_stacks.go +++ b/internal/exec/validate_stacks.go @@ -28,7 +28,7 @@ func ExecuteValidateStacksCmd(cmd *cobra.Command, args []string) error { return err } - cliConfig, err := cfg.InitCliConfig(info, true) + atmosConfig, err := cfg.InitCliConfig(info, true) if err != nil { return err } @@ -41,23 +41,23 @@ func ExecuteValidateStacksCmd(cmd *cobra.Command, args []string) error { } if schemasAtmosManifestFlag != "" { - cliConfig.Schemas.Atmos.Manifest = schemasAtmosManifestFlag + atmosConfig.Schemas.Atmos.Manifest = schemasAtmosManifestFlag } - return ValidateStacks(cliConfig) + return ValidateStacks(atmosConfig) } // ValidateStacks validates Atmos stack configuration -func ValidateStacks(cliConfig schema.CliConfiguration) error { +func ValidateStacks(atmosConfig schema.AtmosConfiguration) error { var validationErrorMessages []string // 1. Process top-level stack manifests and detect duplicate components in the same stack - stacksMap, _, err := FindStacksMap(cliConfig, false) + stacksMap, _, err := FindStacksMap(atmosConfig, false) if err != nil { return err } - terraformComponentStackMap, err := createComponentStackMap(cliConfig, stacksMap, cfg.TerraformSectionName) + terraformComponentStackMap, err := createComponentStackMap(atmosConfig, stacksMap, cfg.TerraformSectionName) if err != nil { return err } @@ -68,7 +68,7 @@ func ValidateStacks(cliConfig schema.CliConfiguration) error { } validationErrorMessages = append(validationErrorMessages, errorList...) - helmfileComponentStackMap, err := createComponentStackMap(cliConfig, stacksMap, cfg.HelmfileSectionName) + helmfileComponentStackMap, err := createComponentStackMap(atmosConfig, stacksMap, cfg.HelmfileSectionName) if err != nil { return err } @@ -86,19 +86,19 @@ func ValidateStacks(cliConfig schema.CliConfiguration) error { // The path to the Atmos manifest JSON Schema can be absolute path or a path relative to the `base_path` setting in `atmos.yaml` var atmosManifestJsonSchemaFilePath string - if cliConfig.Schemas.Atmos.Manifest == "" { - cliConfig.Schemas.Atmos.Manifest = atmosManifestDefault - u.LogTrace(cliConfig, fmt.Sprintf("The Atmos JSON Schema file is not configured. Using the default schema '%s'", atmosManifestDefault)) + if atmosConfig.Schemas.Atmos.Manifest == "" { + atmosConfig.Schemas.Atmos.Manifest = atmosManifestDefault + u.LogTrace(atmosConfig, fmt.Sprintf("The Atmos JSON Schema file is not configured. Using the default schema '%s'", atmosManifestDefault)) } - atmosManifestJsonSchemaFileAbsPath := filepath.Join(cliConfig.BasePath, cliConfig.Schemas.Atmos.Manifest) + atmosManifestJsonSchemaFileAbsPath := filepath.Join(atmosConfig.BasePath, atmosConfig.Schemas.Atmos.Manifest) - if u.FileExists(cliConfig.Schemas.Atmos.Manifest) { - atmosManifestJsonSchemaFilePath = cliConfig.Schemas.Atmos.Manifest + if u.FileExists(atmosConfig.Schemas.Atmos.Manifest) { + atmosManifestJsonSchemaFilePath = atmosConfig.Schemas.Atmos.Manifest } else if u.FileExists(atmosManifestJsonSchemaFileAbsPath) { atmosManifestJsonSchemaFilePath = atmosManifestJsonSchemaFileAbsPath - } else if u.IsURL(cliConfig.Schemas.Atmos.Manifest) { - atmosManifestJsonSchemaFilePath, err = downloadSchemaFromURL(cliConfig.Schemas.Atmos.Manifest) + } else if u.IsURL(atmosConfig.Schemas.Atmos.Manifest) { + atmosManifestJsonSchemaFilePath, err = downloadSchemaFromURL(atmosConfig.Schemas.Atmos.Manifest) if err != nil { return err } @@ -108,7 +108,7 @@ func ValidateStacks(cliConfig schema.CliConfiguration) error { "2. ATMOS_SCHEMAS_ATMOS_MANIFEST env var\n"+ "3. --schemas-atmos-manifest flag\n\n"+ "Accepts: absolute path, paths relative to base_path, or URL", - cliConfig.Schemas.Atmos.Manifest) + atmosConfig.Schemas.Atmos.Manifest) } // Include (process and validate) all YAML files in the `stacks` folder in all subfolders @@ -120,23 +120,23 @@ func ValidateStacks(cliConfig schema.CliConfiguration) error { "**/*.yaml.tmpl", "**/*.yml.tmpl", } - includeStackAbsPaths, err := u.JoinAbsolutePathWithPaths(cliConfig.StacksBaseAbsolutePath, includedPaths) + includeStackAbsPaths, err := u.JoinAbsolutePathWithPaths(atmosConfig.StacksBaseAbsolutePath, includedPaths) if err != nil { return err } - stackConfigFilesAbsolutePaths, _, err := cfg.FindAllStackConfigsInPaths(cliConfig, includeStackAbsPaths, excludedPaths) + stackConfigFilesAbsolutePaths, _, err := cfg.FindAllStackConfigsInPaths(atmosConfig, includeStackAbsPaths, excludedPaths) if err != nil { return err } - u.LogDebug(cliConfig, fmt.Sprintf("Validating all YAML files in the '%s' folder and all subfolders (excluding template files)\n", - filepath.Join(cliConfig.BasePath, cliConfig.Stacks.BasePath))) + u.LogDebug(atmosConfig, fmt.Sprintf("Validating all YAML files in the '%s' folder and all subfolders (excluding template files)\n", + filepath.Join(atmosConfig.BasePath, atmosConfig.Stacks.BasePath))) for _, filePath := range stackConfigFilesAbsolutePaths { stackConfig, importsConfig, _, _, _, err := ProcessYAMLConfigFile( - cliConfig, - cliConfig.StacksBaseAbsolutePath, + atmosConfig, + atmosConfig.StacksBaseAbsolutePath, filePath, map[string]map[string]any{}, nil, @@ -154,10 +154,10 @@ func ValidateStacks(cliConfig schema.CliConfiguration) error { // Process and validate the stack manifest _, err = ProcessStackConfig( - cliConfig, - cliConfig.StacksBaseAbsolutePath, - cliConfig.TerraformDirAbsolutePath, - cliConfig.HelmfileDirAbsolutePath, + atmosConfig, + atmosConfig.StacksBaseAbsolutePath, + atmosConfig.TerraformDirAbsolutePath, + atmosConfig.HelmfileDirAbsolutePath, filePath, stackConfig, false, @@ -180,7 +180,7 @@ func ValidateStacks(cliConfig schema.CliConfiguration) error { } func createComponentStackMap( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, stacksMap map[string]any, componentType string, ) (map[string]map[string][]string, error) { @@ -263,15 +263,15 @@ func createComponentStackMap( } // Find Atmos stack name - if cliConfig.Stacks.NameTemplate != "" { - stackName, err = ProcessTmpl("validate-stacks-name-template", cliConfig.Stacks.NameTemplate, configAndStacksInfo.ComponentSection, false) + if atmosConfig.Stacks.NameTemplate != "" { + stackName, err = ProcessTmpl("validate-stacks-name-template", atmosConfig.Stacks.NameTemplate, configAndStacksInfo.ComponentSection, false) if err != nil { return nil, err } } else { context := cfg.GetContextFromVars(varsSection) configAndStacksInfo.Context = context - stackName, err = cfg.GetContextPrefix(stackManifest, context, GetStackNamePattern(cliConfig), stackManifest) + stackName, err = cfg.GetContextPrefix(stackManifest, context, GetStackNamePattern(atmosConfig), stackManifest) if err != nil { return nil, err } diff --git a/internal/exec/vendor_component_utils.go b/internal/exec/vendor_component_utils.go index 205bedba3..a3370eeb1 100644 --- a/internal/exec/vendor_component_utils.go +++ b/internal/exec/vendor_component_utils.go @@ -35,7 +35,7 @@ func findComponentConfigFile(basePath, fileName string) (string, error) { // ReadAndProcessComponentVendorConfigFile reads and processes the component vendoring config file `component.yaml` func ReadAndProcessComponentVendorConfigFile( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, component string, componentType string, ) (schema.VendorComponentConfig, string, error) { @@ -43,14 +43,14 @@ func ReadAndProcessComponentVendorConfigFile( var componentConfig schema.VendorComponentConfig if componentType == "terraform" { - componentBasePath = cliConfig.Components.Terraform.BasePath + componentBasePath = atmosConfig.Components.Terraform.BasePath } else if componentType == "helmfile" { - componentBasePath = cliConfig.Components.Helmfile.BasePath + componentBasePath = atmosConfig.Components.Helmfile.BasePath } else { return componentConfig, "", fmt.Errorf("type '%s' is not supported. Valid types are 'terraform' and 'helmfile'", componentType) } - componentPath := filepath.Join(cliConfig.BasePath, componentBasePath, component) + componentPath := filepath.Join(atmosConfig.BasePath, componentBasePath, component) dirExists, err := u.IsDirectory(componentPath) if err != nil { @@ -102,7 +102,7 @@ func ExecuteStackVendorInternal( ) error { return fmt.Errorf("command 'atmos vendor pull --stack ' is not supported yet") } -func copyComponentToDestination(cliConfig schema.CliConfiguration, tempDir, componentPath string, vendorComponentSpec schema.VendorComponentSpec, sourceIsLocalFile bool, uri string) error { +func copyComponentToDestination(atmosConfig schema.AtmosConfiguration, tempDir, componentPath string, vendorComponentSpec schema.VendorComponentSpec, sourceIsLocalFile bool, uri string) error { // Copy from the temp folder to the destination folder and skip the excluded files copyOptions := cp.Options{ // Skip specifies which files should be skipped @@ -123,7 +123,7 @@ func copyComponentToDestination(cliConfig schema.CliConfiguration, tempDir, comp return true, err } else if excludeMatch { // If the file matches ANY of the 'excluded_paths' patterns, exclude the file - u.LogTrace(cliConfig, fmt.Sprintf("Excluding the file '%s' since it matches the '%s' pattern from 'excluded_paths'\n", + u.LogTrace(atmosConfig, fmt.Sprintf("Excluding the file '%s' since it matches the '%s' pattern from 'excluded_paths'\n", trimmedSrc, excludePath, )) @@ -140,7 +140,7 @@ func copyComponentToDestination(cliConfig schema.CliConfiguration, tempDir, comp return true, err } else if includeMatch { // If the file matches ANY of the 'included_paths' patterns, include the file - u.LogTrace(cliConfig, fmt.Sprintf("Including '%s' since it matches the '%s' pattern from 'included_paths'\n", + u.LogTrace(atmosConfig, fmt.Sprintf("Including '%s' since it matches the '%s' pattern from 'included_paths'\n", trimmedSrc, includePath, )) @@ -152,13 +152,13 @@ func copyComponentToDestination(cliConfig schema.CliConfiguration, tempDir, comp if anyMatches { return false, nil } else { - u.LogTrace(cliConfig, fmt.Sprintf("Excluding '%s' since it does not match any pattern from 'included_paths'\n", trimmedSrc)) + u.LogTrace(atmosConfig, fmt.Sprintf("Excluding '%s' since it does not match any pattern from 'included_paths'\n", trimmedSrc)) return true, nil } } // If 'included_paths' is not provided, include all files that were not excluded - u.LogTrace(cliConfig, fmt.Sprintf("Including '%s'\n", u.TrimBasePathFromPath(tempDir+"/", src))) + u.LogTrace(atmosConfig, fmt.Sprintf("Including '%s'\n", u.TrimBasePathFromPath(tempDir+"/", src))) return false, nil }, @@ -189,7 +189,7 @@ func copyComponentToDestination(cliConfig schema.CliConfiguration, tempDir, comp return nil } func ExecuteComponentVendorInternal( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, vendorComponentSpec schema.VendorComponentSpec, component string, componentPath string, @@ -338,7 +338,7 @@ func ExecuteComponentVendorInternal( } // Run TUI to process packages if len(packages) > 0 { - model, err := newModelComponentVendorInternal(packages, dryRun, cliConfig) + model, err := newModelComponentVendorInternal(packages, dryRun, atmosConfig) if err != nil { return fmt.Errorf("error initializing model: %v", err) } @@ -346,7 +346,7 @@ func ExecuteComponentVendorInternal( // Disable TUI if no TTY support is available if !CheckTTYSupport() { opts = []tea.ProgramOption{tea.WithoutRenderer(), tea.WithInput(nil)} - u.LogWarning(cliConfig, "TTY is not supported. Running in non-interactive mode") + u.LogWarning(atmosConfig, "TTY is not supported. Running in non-interactive mode") } if _, err := tea.NewProgram(&model, opts...).Run(); err != nil { return fmt.Errorf("running download error: %w", err) diff --git a/internal/exec/vendor_model.go b/internal/exec/vendor_model.go index 2ab2dd8a7..7171f73ec 100644 --- a/internal/exec/vendor_model.go +++ b/internal/exec/vendor_model.go @@ -53,17 +53,17 @@ type pkgAtmosVendor struct { } type modelVendor struct { - packages []pkgVendor - index int - width int - height int - spinner spinner.Model - progress progress.Model - done bool - dryRun bool - failedPkg int - cliConfig schema.CliConfiguration - isTTY bool + packages []pkgVendor + index int + width int + height int + spinner spinner.Model + progress progress.Model + done bool + dryRun bool + failedPkg int + atmosConfig schema.AtmosConfiguration + isTTY bool } var ( @@ -74,7 +74,7 @@ var ( grayColor = lipgloss.NewStyle().Foreground(lipgloss.Color("241")) ) -func newModelAtmosVendorInternal(pkgs []pkgAtmosVendor, dryRun bool, cliConfig schema.CliConfiguration) (modelVendor, error) { +func newModelAtmosVendorInternal(pkgs []pkgAtmosVendor, dryRun bool, atmosConfig schema.AtmosConfiguration) (modelVendor, error) { p := progress.New( progress.WithDefaultGradient(), progress.WithWidth(30), @@ -96,12 +96,12 @@ func newModelAtmosVendorInternal(pkgs []pkgAtmosVendor, dryRun bool, cliConfig s vendorPks = append(vendorPks, p) } return modelVendor{ - packages: vendorPks, - spinner: s, - progress: p, - dryRun: dryRun, - cliConfig: cliConfig, - isTTY: tty, + packages: vendorPks, + spinner: s, + progress: p, + dryRun: dryRun, + atmosConfig: atmosConfig, + isTTY: tty, }, nil } @@ -110,7 +110,7 @@ func (m *modelVendor) Init() tea.Cmd { m.done = true return nil } - return tea.Batch(ExecuteInstall(m.packages[0], m.dryRun, m.cliConfig), m.spinner.Tick) + return tea.Batch(ExecuteInstall(m.packages[0], m.dryRun, m.atmosConfig), m.spinner.Tick) } func (m *modelVendor) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { @@ -137,7 +137,7 @@ func (m *modelVendor) Update(msg tea.Msg) (tea.Model, tea.Cmd) { if msg.err != nil { errMsg = fmt.Sprintf("Failed to vendor %s: error : %s", pkg.name, msg.err) if !m.isTTY { - u.LogError(m.cliConfig, errors.New(errMsg)) + u.LogError(m.atmosConfig, errors.New(errMsg)) } mark = xMark m.failedPkg++ @@ -150,14 +150,14 @@ func (m *modelVendor) Update(msg tea.Msg) (tea.Model, tea.Cmd) { // Everything's been installed. We're done! m.done = true if !m.isTTY { - u.LogInfo(m.cliConfig, fmt.Sprintf("%s %s %s", mark, pkg.name, version)) + u.LogInfo(m.atmosConfig, fmt.Sprintf("%s %s %s", mark, pkg.name, version)) if m.dryRun { - u.LogInfo(m.cliConfig, "Done! Dry run completed. No components vendored.\n") + u.LogInfo(m.atmosConfig, "Done! Dry run completed. No components vendored.\n") } if m.failedPkg > 0 { - u.LogInfo(m.cliConfig, fmt.Sprintf("Vendored %d components. Failed to vendor %d components.\n", len(m.packages)-m.failedPkg, m.failedPkg)) + u.LogInfo(m.atmosConfig, fmt.Sprintf("Vendored %d components. Failed to vendor %d components.\n", len(m.packages)-m.failedPkg, m.failedPkg)) } - u.LogInfo(m.cliConfig, fmt.Sprintf("Vendored %d components.\n", len(m.packages))) + u.LogInfo(m.atmosConfig, fmt.Sprintf("Vendored %d components.\n", len(m.packages))) } version := grayColor.Render(version) return m, tea.Sequence( @@ -166,7 +166,7 @@ func (m *modelVendor) Update(msg tea.Msg) (tea.Model, tea.Cmd) { ) } if !m.isTTY { - u.LogInfo(m.cliConfig, fmt.Sprintf("%s %s %s", mark, pkg.name, version)) + u.LogInfo(m.atmosConfig, fmt.Sprintf("%s %s %s", mark, pkg.name, version)) } m.index++ // Update progress bar @@ -175,8 +175,8 @@ func (m *modelVendor) Update(msg tea.Msg) (tea.Model, tea.Cmd) { version = grayColor.Render(version) return m, tea.Batch( progressCmd, - tea.Printf("%s %s %s %s", mark, pkg.name, version, errMsg), // print message above our program - ExecuteInstall(m.packages[m.index], m.dryRun, m.cliConfig), // download the next package + tea.Printf("%s %s %s %s", mark, pkg.name, version, errMsg), // print message above our program + ExecuteInstall(m.packages[m.index], m.dryRun, m.atmosConfig), // download the next package ) case spinner.TickMsg: var cmd tea.Cmd @@ -234,7 +234,7 @@ func max(a, b int) int { } return b } -func downloadAndInstall(p *pkgAtmosVendor, dryRun bool, cliConfig schema.CliConfiguration) tea.Cmd { +func downloadAndInstall(p *pkgAtmosVendor, dryRun bool, atmosConfig schema.AtmosConfiguration) tea.Cmd { return func() tea.Msg { if dryRun { // Simulate the action @@ -261,7 +261,7 @@ func downloadAndInstall(p *pkgAtmosVendor, dryRun bool, cliConfig schema.CliConf } } - defer removeTempDir(cliConfig, tempDir) + defer removeTempDir(atmosConfig, tempDir) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute) defer cancel() @@ -283,7 +283,7 @@ func downloadAndInstall(p *pkgAtmosVendor, dryRun bool, cliConfig schema.CliConf case pkgTypeOci: // Process OCI images - if err := processOciImage(cliConfig, p.uri, tempDir); err != nil { + if err := processOciImage(atmosConfig, p.uri, tempDir); err != nil { return installedPkgMsg{ err: fmt.Errorf("failed to process OCI image: %w", err), name: p.name, @@ -313,7 +313,7 @@ func downloadAndInstall(p *pkgAtmosVendor, dryRun bool, cliConfig schema.CliConf } } - if err := copyToTarget(cliConfig, tempDir, p.targetPath, &p.atmosVendorSource, p.sourceIsLocalFile, p.uri); err != nil { + if err := copyToTarget(atmosConfig, tempDir, p.targetPath, &p.atmosVendorSource, p.sourceIsLocalFile, p.uri); err != nil { return installedPkgMsg{ err: fmt.Errorf("failed to copy package: %w", err), name: p.name, @@ -326,13 +326,13 @@ func downloadAndInstall(p *pkgAtmosVendor, dryRun bool, cliConfig schema.CliConf } } -func ExecuteInstall(installer pkgVendor, dryRun bool, cliConfig schema.CliConfiguration) tea.Cmd { +func ExecuteInstall(installer pkgVendor, dryRun bool, atmosConfig schema.AtmosConfiguration) tea.Cmd { if installer.atmosPackage != nil { - return downloadAndInstall(installer.atmosPackage, dryRun, cliConfig) + return downloadAndInstall(installer.atmosPackage, dryRun, atmosConfig) } if installer.componentPackage != nil { - return downloadComponentAndInstall(installer.componentPackage, dryRun, cliConfig) + return downloadComponentAndInstall(installer.componentPackage, dryRun, atmosConfig) } // No valid package provided diff --git a/internal/exec/vendor_model_component.go b/internal/exec/vendor_model_component.go index 8207b3632..213140a64 100644 --- a/internal/exec/vendor_model_component.go +++ b/internal/exec/vendor_model_component.go @@ -30,7 +30,7 @@ type pkgComponentVendor struct { mixinFilename string } -func newModelComponentVendorInternal(pkgs []pkgComponentVendor, dryRun bool, cliConfig schema.CliConfiguration) (modelVendor, error) { +func newModelComponentVendorInternal(pkgs []pkgComponentVendor, dryRun bool, atmosConfig schema.AtmosConfiguration) (modelVendor, error) { p := progress.New( progress.WithDefaultGradient(), progress.WithWidth(30), @@ -53,16 +53,16 @@ func newModelComponentVendorInternal(pkgs []pkgComponentVendor, dryRun bool, cli } tty := CheckTTYSupport() return modelVendor{ - packages: vendorPks, - spinner: s, - progress: p, - dryRun: dryRun, - cliConfig: cliConfig, - isTTY: tty, + packages: vendorPks, + spinner: s, + progress: p, + dryRun: dryRun, + atmosConfig: atmosConfig, + isTTY: tty, }, nil } -func downloadComponentAndInstall(p *pkgComponentVendor, dryRun bool, cliConfig schema.CliConfiguration) tea.Cmd { +func downloadComponentAndInstall(p *pkgComponentVendor, dryRun bool, atmosConfig schema.AtmosConfiguration) tea.Cmd { return func() tea.Msg { if dryRun { // Simulate the action @@ -73,7 +73,7 @@ func downloadComponentAndInstall(p *pkgComponentVendor, dryRun bool, cliConfig s } } if p.IsComponent { - err := installComponent(p, cliConfig) + err := installComponent(p, atmosConfig) if err != nil { return installedPkgMsg{ err: err, @@ -87,7 +87,7 @@ func downloadComponentAndInstall(p *pkgComponentVendor, dryRun bool, cliConfig s } } if p.IsMixins { - err := installMixin(p, cliConfig) + err := installMixin(p, atmosConfig) if err != nil { return installedPkgMsg{ err: err, @@ -106,7 +106,7 @@ func downloadComponentAndInstall(p *pkgComponentVendor, dryRun bool, cliConfig s } } } -func installComponent(p *pkgComponentVendor, cliConfig schema.CliConfiguration) error { +func installComponent(p *pkgComponentVendor, atmosConfig schema.AtmosConfiguration) error { // Create temp folder // We are using a temp folder for the following reasons: @@ -120,7 +120,7 @@ func installComponent(p *pkgComponentVendor, cliConfig schema.CliConfiguration) if err := os.Chmod(tempDir, 0700); err != nil { return fmt.Errorf("failed to set temp directory permissions: %w", err) } - defer removeTempDir(cliConfig, tempDir) + defer removeTempDir(atmosConfig, tempDir) switch p.pkgType { case pkgTypeRemote: @@ -141,7 +141,7 @@ func installComponent(p *pkgComponentVendor, cliConfig schema.CliConfiguration) case pkgTypeOci: // Download the Image from the OCI-compatible registry, extract the layers from the tarball, and write to the destination directory - err = processOciImage(cliConfig, p.uri, tempDir) + err = processOciImage(atmosConfig, p.uri, tempDir) if err != nil { return fmt.Errorf("Failed to process OCI image %s error %s", p.name, err) } @@ -169,20 +169,20 @@ func installComponent(p *pkgComponentVendor, cliConfig schema.CliConfiguration) return fmt.Errorf("unknown package type %s package %s", p.pkgType.String(), p.name) } - if err = copyComponentToDestination(cliConfig, tempDir, p.componentPath, p.vendorComponentSpec, p.sourceIsLocalFile, p.uri); err != nil { + if err = copyComponentToDestination(atmosConfig, tempDir, p.componentPath, p.vendorComponentSpec, p.sourceIsLocalFile, p.uri); err != nil { return fmt.Errorf("failed to copy package %s error %s", p.name, err) } return nil } -func installMixin(p *pkgComponentVendor, cliConfig schema.CliConfiguration) error { +func installMixin(p *pkgComponentVendor, atmosConfig schema.AtmosConfiguration) error { tempDir, err := os.MkdirTemp("", strconv.FormatInt(time.Now().Unix(), 10)) if err != nil { return fmt.Errorf("Failed to create temp directory %s", err) } - defer removeTempDir(cliConfig, tempDir) + defer removeTempDir(atmosConfig, tempDir) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute) defer cancel() switch p.pkgType { @@ -199,7 +199,7 @@ func installMixin(p *pkgComponentVendor, cliConfig schema.CliConfiguration) erro } case pkgTypeOci: // Download the Image from the OCI-compatible registry, extract the layers from the tarball, and write to the destination directory - err = processOciImage(cliConfig, p.uri, tempDir) + err = processOciImage(atmosConfig, p.uri, tempDir) if err != nil { return fmt.Errorf("Failed to process OCI image %s error %s", p.name, err) } diff --git a/internal/exec/vendor_utils.go b/internal/exec/vendor_utils.go index 4fe63c9b4..eee8ab995 100644 --- a/internal/exec/vendor_utils.go +++ b/internal/exec/vendor_utils.go @@ -34,7 +34,7 @@ func ExecuteVendorPullCommand(cmd *cobra.Command, args []string) error { // InitCliConfig finds and merges CLI configurations in the following order: // system dir, home dir, current dir, ENV vars, command-line arguments - cliConfig, err := cfg.InitCliConfig(info, processStacks) + atmosConfig, err := cfg.InitCliConfig(info, processStacks) if err != nil { return fmt.Errorf("failed to initialize CLI config: %w", err) } @@ -94,7 +94,7 @@ func ExecuteVendorPullCommand(cmd *cobra.Command, args []string) error { } // Check `vendor.yaml` - vendorConfig, vendorConfigExists, foundVendorConfigFile, err := ReadAndProcessVendorConfigFile(cliConfig, cfg.AtmosVendorConfigFileName, true) + vendorConfig, vendorConfigExists, foundVendorConfigFile, err := ReadAndProcessVendorConfigFile(atmosConfig, cfg.AtmosVendorConfigFileName, true) if err != nil { return err } @@ -103,7 +103,7 @@ func ExecuteVendorPullCommand(cmd *cobra.Command, args []string) error { } if vendorConfigExists { // Process `vendor.yaml` - return ExecuteAtmosVendorInternal(cliConfig, foundVendorConfigFile, vendorConfig.Spec, component, tags, dryRun) + return ExecuteAtmosVendorInternal(atmosConfig, foundVendorConfigFile, vendorConfig.Spec, component, tags, dryRun) } else { // Check and process `component.yaml` if component != "" { @@ -117,12 +117,12 @@ func ExecuteVendorPullCommand(cmd *cobra.Command, args []string) error { componentType = "terraform" } - componentConfig, componentPath, err := ReadAndProcessComponentVendorConfigFile(cliConfig, component, componentType) + componentConfig, componentPath, err := ReadAndProcessComponentVendorConfigFile(atmosConfig, component, componentType) if err != nil { return err } - return ExecuteComponentVendorInternal(cliConfig, componentConfig.Spec, component, componentPath, dryRun) + return ExecuteComponentVendorInternal(atmosConfig, componentConfig.Spec, component, componentPath, dryRun) } } @@ -138,7 +138,7 @@ func ExecuteVendorPullCommand(cmd *cobra.Command, args []string) error { // ReadAndProcessVendorConfigFile reads and processes the Atmos vendoring config file `vendor.yaml` func ReadAndProcessVendorConfigFile( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, vendorConfigFile string, checkGlobalConfig bool, ) (schema.AtmosVendorConfig, bool, string, error) { @@ -151,11 +151,11 @@ func ReadAndProcessVendorConfigFile( var foundVendorConfigFile string // Check if vendor config is specified in atmos.yaml - if checkGlobalConfig && cliConfig.Vendor.BasePath != "" { - if !filepath.IsAbs(cliConfig.Vendor.BasePath) { - foundVendorConfigFile = filepath.Join(cliConfig.BasePath, cliConfig.Vendor.BasePath) + if checkGlobalConfig && atmosConfig.Vendor.BasePath != "" { + if !filepath.IsAbs(atmosConfig.Vendor.BasePath) { + foundVendorConfigFile = filepath.Join(atmosConfig.BasePath, atmosConfig.Vendor.BasePath) } else { - foundVendorConfigFile = cliConfig.Vendor.BasePath + foundVendorConfigFile = atmosConfig.Vendor.BasePath } } else { // Path is not defined in atmos.yaml, proceed with existing logic @@ -164,12 +164,12 @@ func ReadAndProcessVendorConfigFile( if !fileExists { // Look for the vendoring manifest in the directory pointed to by the `base_path` setting in `atmos.yaml` - pathToVendorConfig := filepath.Join(cliConfig.BasePath, vendorConfigFile) + pathToVendorConfig := filepath.Join(atmosConfig.BasePath, vendorConfigFile) foundVendorConfigFile, fileExists = u.SearchConfigFile(pathToVendorConfig) if !fileExists { vendorConfigFileExists = false - u.LogWarning(cliConfig, fmt.Sprintf("Vendor config file '%s' does not exist. Proceeding without vendor configurations", pathToVendorConfig)) + u.LogWarning(atmosConfig, fmt.Sprintf("Vendor config file '%s' does not exist. Proceeding without vendor configurations", pathToVendorConfig)) return vendorConfig, vendorConfigFileExists, "", nil } } @@ -248,7 +248,7 @@ func ReadAndProcessVendorConfigFile( // ExecuteAtmosVendorInternal downloads the artifacts from the sources and writes them to the targets func ExecuteAtmosVendorInternal( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, vendorConfigFileName string, atmosVendorSpec schema.AtmosVendorSpec, component string, @@ -259,7 +259,7 @@ func ExecuteAtmosVendorInternal( var err error vendorConfigFilePath := filepath.Dir(vendorConfigFileName) - logInitialMessage(cliConfig, vendorConfigFileName, tags) + logInitialMessage(atmosConfig, vendorConfigFileName, tags) if len(atmosVendorSpec.Sources) == 0 && len(atmosVendorSpec.Imports) == 0 { return fmt.Errorf("either 'spec.sources' or 'spec.imports' (or both) must be defined in the vendor config file '%s'", vendorConfigFileName) @@ -267,7 +267,7 @@ func ExecuteAtmosVendorInternal( // Process imports and return all sources from all the imports and from `vendor.yaml` sources, _, err := processVendorImports( - cliConfig, + atmosConfig, vendorConfigFileName, atmosVendorSpec.Imports, atmosVendorSpec.Sources, @@ -402,10 +402,10 @@ func ExecuteAtmosVendorInternal( if !CheckTTYSupport() { // set tea.WithInput(nil) workaround tea program not run on not TTY mod issue on non TTY mode https://github.com/charmbracelet/bubbletea/issues/761 opts = []tea.ProgramOption{tea.WithoutRenderer(), tea.WithInput(nil)} - u.LogWarning(cliConfig, "No TTY detected. Falling back to basic output. This can happen when no terminal is attached or when commands are pipelined.") + u.LogWarning(atmosConfig, "No TTY detected. Falling back to basic output. This can happen when no terminal is attached or when commands are pipelined.") } - model, err := newModelAtmosVendorInternal(packages, dryRun, cliConfig) + model, err := newModelAtmosVendorInternal(packages, dryRun, atmosConfig) if err != nil { return fmt.Errorf("failed to initialize TUI model: %v (verify terminal capabilities and permissions)", err) } @@ -419,7 +419,7 @@ func ExecuteAtmosVendorInternal( // processVendorImports processes all imports recursively and returns a list of sources func processVendorImports( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, vendorConfigFile string, imports []string, sources []schema.AtmosVendorSource, @@ -437,7 +437,7 @@ func processVendorImports( allImports = append(allImports, imp) - vendorConfig, _, _, err := ReadAndProcessVendorConfigFile(cliConfig, imp, false) + vendorConfig, _, _, err := ReadAndProcessVendorConfigFile(atmosConfig, imp, false) if err != nil { return nil, nil, err } @@ -450,7 +450,7 @@ func processVendorImports( return nil, nil, fmt.Errorf("either 'spec.sources' or 'spec.imports' (or both) must be defined in the vendor config file '%s'", imp) } - mergedSources, allImports, err = processVendorImports(cliConfig, imp, vendorConfig.Spec.Imports, mergedSources, allImports) + mergedSources, allImports, err = processVendorImports(atmosConfig, imp, vendorConfig.Spec.Imports, mergedSources, allImports) if err != nil { return nil, nil, err } @@ -465,12 +465,12 @@ func processVendorImports( return append(mergedSources, sources...), allImports, nil } -func logInitialMessage(cliConfig schema.CliConfiguration, vendorConfigFileName string, tags []string) { +func logInitialMessage(atmosConfig schema.AtmosConfiguration, vendorConfigFileName string, tags []string) { logMessage := fmt.Sprintf("Vendoring from '%s'", vendorConfigFileName) if len(tags) > 0 { logMessage = fmt.Sprintf("%s for tags {%s}", logMessage, strings.Join(tags, ", ")) } - u.LogInfo(cliConfig, logMessage) + u.LogInfo(atmosConfig, logMessage) } func validateSourceFields(s *schema.AtmosVendorSource, vendorConfigFileName string) error { @@ -513,9 +513,9 @@ func determineSourceType(uri *string, vendorConfigFilePath string) (bool, bool, return useOciScheme, useLocalFileSystem, sourceIsLocalFile } -func copyToTarget(cliConfig schema.CliConfiguration, tempDir, targetPath string, s *schema.AtmosVendorSource, sourceIsLocalFile bool, uri string) error { +func copyToTarget(atmosConfig schema.AtmosConfiguration, tempDir, targetPath string, s *schema.AtmosVendorSource, sourceIsLocalFile bool, uri string) error { copyOptions := cp.Options{ - Skip: generateSkipFunction(cliConfig, tempDir, s), + Skip: generateSkipFunction(atmosConfig, tempDir, s), PreserveTimes: false, PreserveOwner: false, OnSymlink: func(src string) cp.SymlinkAction { return cp.Deep }, @@ -534,12 +534,12 @@ func copyToTarget(cliConfig schema.CliConfiguration, tempDir, targetPath string, // and IncludedPaths to filter files during the copy operation. // // Parameters: -// - cliConfig: The CLI configuration for logging +// - atmosConfig: The CLI configuration for logging // - tempDir: The temporary directory containing the files to copy // - s: The vendor source configuration containing exclusion/inclusion patterns // // Returns a function that determines if a file should be skipped during copying -func generateSkipFunction(cliConfig schema.CliConfiguration, tempDir string, s *schema.AtmosVendorSource) func(os.FileInfo, string, string) (bool, error) { +func generateSkipFunction(atmosConfig schema.AtmosConfiguration, tempDir string, s *schema.AtmosVendorSource) func(os.FileInfo, string, string) (bool, error) { return func(srcInfo os.FileInfo, src, dest string) (bool, error) { if filepath.Base(src) == ".git" { return true, nil @@ -557,7 +557,7 @@ func generateSkipFunction(cliConfig schema.CliConfiguration, tempDir string, s * return true, err } else if excludeMatch { // If the file matches ANY of the 'excluded_paths' patterns, exclude the file - u.LogTrace(cliConfig, fmt.Sprintf("Excluding the file '%s' since it matches the '%s' pattern from 'excluded_paths'\n", + u.LogTrace(atmosConfig, fmt.Sprintf("Excluding the file '%s' since it matches the '%s' pattern from 'excluded_paths'\n", trimmedSrc, excludePath, )) @@ -574,7 +574,7 @@ func generateSkipFunction(cliConfig schema.CliConfiguration, tempDir string, s * return true, err } else if includeMatch { // If the file matches ANY of the 'included_paths' patterns, include the file - u.LogTrace(cliConfig, fmt.Sprintf("Including '%s' since it matches the '%s' pattern from 'included_paths'\n", + u.LogTrace(atmosConfig, fmt.Sprintf("Including '%s' since it matches the '%s' pattern from 'included_paths'\n", trimmedSrc, includePath, )) @@ -586,13 +586,13 @@ func generateSkipFunction(cliConfig schema.CliConfiguration, tempDir string, s * if anyMatches { return false, nil } else { - u.LogTrace(cliConfig, fmt.Sprintf("Excluding '%s' since it does not match any pattern from 'included_paths'\n", trimmedSrc)) + u.LogTrace(atmosConfig, fmt.Sprintf("Excluding '%s' since it does not match any pattern from 'included_paths'\n", trimmedSrc)) return true, nil } } // If 'included_paths' is not provided, include all files that were not excluded - u.LogTrace(cliConfig, fmt.Sprintf("Including '%s'\n", u.TrimBasePathFromPath(tempDir+"/", src))) + u.LogTrace(atmosConfig, fmt.Sprintf("Including '%s'\n", u.TrimBasePathFromPath(tempDir+"/", src))) return false, nil } } diff --git a/internal/exec/workflow.go b/internal/exec/workflow.go index 9a229cb3f..ab901a729 100644 --- a/internal/exec/workflow.go +++ b/internal/exec/workflow.go @@ -26,14 +26,14 @@ func ExecuteWorkflowCmd(cmd *cobra.Command, args []string) error { // InitCliConfig finds and merges CLI configurations in the following order: // system dir, home dir, current dir, ENV vars, command-line arguments - cliConfig, err := cfg.InitCliConfig(info, true) + atmosConfig, err := cfg.InitCliConfig(info, true) if err != nil { return err } // If the `workflow` argument is not passed, start the workflow UI if len(args) != 1 { - workflowFile, workflow, fromStep, err = ExecuteWorkflowUI(cliConfig) + workflowFile, workflow, fromStep, err = ExecuteWorkflowUI(atmosConfig) if err != nil { return err } @@ -79,7 +79,7 @@ func ExecuteWorkflowCmd(cmd *cobra.Command, args []string) error { if u.IsPathAbsolute(workflowFile) { workflowPath = workflowFile } else { - workflowPath = filepath.Join(cliConfig.BasePath, cliConfig.Workflows.BasePath, workflowFile) + workflowPath = filepath.Join(atmosConfig.BasePath, atmosConfig.Workflows.BasePath, workflowFile) } // If the workflow file is specified without an extension, use the default extension @@ -119,7 +119,7 @@ func ExecuteWorkflowCmd(cmd *cobra.Command, args []string) error { workflowDefinition = i } - err = ExecuteWorkflow(cliConfig, workflow, workflowPath, &workflowDefinition, dryRun, commandLineStack, fromStep) + err = ExecuteWorkflow(atmosConfig, workflow, workflowPath, &workflowDefinition, dryRun, commandLineStack, fromStep) if err != nil { return err } diff --git a/internal/exec/workflow_utils.go b/internal/exec/workflow_utils.go index a21713d4a..06fdd53fa 100644 --- a/internal/exec/workflow_utils.go +++ b/internal/exec/workflow_utils.go @@ -18,7 +18,7 @@ import ( // ExecuteWorkflow executes an Atmos workflow func ExecuteWorkflow( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, workflow string, workflowPath string, workflowDefinition *schema.WorkflowDefinition, @@ -40,10 +40,10 @@ func ExecuteWorkflow( // Check if the workflow steps have the `name` attribute checkAndGenerateWorkflowStepNames(workflowDefinition) - logFunc(cliConfig, fmt.Sprintf("\nExecuting the workflow '%s' from '%s'\n", workflow, workflowPath)) + logFunc(atmosConfig, fmt.Sprintf("\nExecuting the workflow '%s' from '%s'\n", workflow, workflowPath)) - if cliConfig.Logs.Level == u.LogLevelTrace || cliConfig.Logs.Level == u.LogLevelDebug { - err := u.PrintAsYAMLToFileDescriptor(cliConfig, workflowDefinition) + if atmosConfig.Logs.Level == u.LogLevelTrace || atmosConfig.Logs.Level == u.LogLevelDebug { + err := u.PrintAsYAMLToFileDescriptor(atmosConfig, workflowDefinition) if err != nil { return err } @@ -64,7 +64,7 @@ func ExecuteWorkflow( var command = strings.TrimSpace(step.Command) var commandType = strings.TrimSpace(step.Type) - logFunc(cliConfig, fmt.Sprintf("Executing workflow step: %s", command)) + logFunc(atmosConfig, fmt.Sprintf("Executing workflow step: %s", command)) if commandType == "" { commandType = "atmos" @@ -73,7 +73,7 @@ func ExecuteWorkflow( var err error if commandType == "shell" { commandName := fmt.Sprintf("%s-step-%d", workflow, stepIdx) - err = ExecuteShell(cliConfig, command, commandName, ".", []string{}, dryRun) + err = ExecuteShell(atmosConfig, command, commandName, ".", []string{}, dryRun) } else if commandType == "atmos" { args := strings.Fields(command) @@ -97,10 +97,10 @@ func ExecuteWorkflow( if finalStack != "" { args = append(args, []string{"-s", finalStack}...) - logFunc(cliConfig, fmt.Sprintf("Stack: %s", finalStack)) + logFunc(atmosConfig, fmt.Sprintf("Stack: %s", finalStack)) } - err = ExecuteShellCommand(cliConfig, "atmos", args, ".", []string{}, dryRun, "") + err = ExecuteShellCommand(atmosConfig, "atmos", args, ".", []string{}, dryRun, "") } else { return fmt.Errorf("invalid workflow step type '%s'. Supported types are 'atmos' and 'shell'", commandType) } @@ -111,8 +111,8 @@ func ExecuteWorkflow( failedMsg := color.New(color.FgRed).Sprintf("\nStep '%s' failed!", step.Name) - u.LogDebug(cliConfig, fmt.Sprintf("\nCommand failed: %s", command)) - u.LogDebug(cliConfig, fmt.Sprintf("Error: %v", err)) + u.LogDebug(atmosConfig, fmt.Sprintf("\nCommand failed: %s", command)) + u.LogDebug(atmosConfig, fmt.Sprintf("Error: %v", err)) resumeMsg := color.New(color.FgGreen).Sprintf( "\nTo resume the workflow from this step, run:\natmos workflow %s -f %s --from-step %s", @@ -130,23 +130,23 @@ func ExecuteWorkflow( // ExecuteDescribeWorkflows executes `atmos describe workflows` command func ExecuteDescribeWorkflows( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, ) ([]schema.DescribeWorkflowsItem, map[string][]string, map[string]schema.WorkflowManifest, error) { listResult := []schema.DescribeWorkflowsItem{} mapResult := make(map[string][]string) allResult := make(map[string]schema.WorkflowManifest) - if cliConfig.Workflows.BasePath == "" { + if atmosConfig.Workflows.BasePath == "" { return nil, nil, nil, errors.New("'workflows.base_path' must be configured in 'atmos.yaml'") } // If `workflows.base_path` is a relative path, join it with `stacks.base_path` var workflowsDir string - if u.IsPathAbsolute(cliConfig.Workflows.BasePath) { - workflowsDir = cliConfig.Workflows.BasePath + if u.IsPathAbsolute(atmosConfig.Workflows.BasePath) { + workflowsDir = atmosConfig.Workflows.BasePath } else { - workflowsDir = filepath.Join(cliConfig.BasePath, cliConfig.Workflows.BasePath) + workflowsDir = filepath.Join(atmosConfig.BasePath, atmosConfig.Workflows.BasePath) } isDirectory, err := u.IsDirectory(workflowsDir) @@ -157,15 +157,15 @@ func ExecuteDescribeWorkflows( files, err := u.GetAllYamlFilesInDir(workflowsDir) if err != nil { return nil, nil, nil, fmt.Errorf("error reading the directory '%s' defined in 'workflows.base_path' in 'atmos.yaml': %v", - cliConfig.Workflows.BasePath, err) + atmosConfig.Workflows.BasePath, err) } for _, f := range files { var workflowPath string - if u.IsPathAbsolute(cliConfig.Workflows.BasePath) { - workflowPath = filepath.Join(cliConfig.Workflows.BasePath, f) + if u.IsPathAbsolute(atmosConfig.Workflows.BasePath) { + workflowPath = filepath.Join(atmosConfig.Workflows.BasePath, f) } else { - workflowPath = filepath.Join(cliConfig.BasePath, cliConfig.Workflows.BasePath, f) + workflowPath = filepath.Join(atmosConfig.BasePath, atmosConfig.Workflows.BasePath, f) } fileContent, err := os.ReadFile(workflowPath) @@ -231,8 +231,8 @@ func checkAndGenerateWorkflowStepNames(workflowDefinition *schema.WorkflowDefini } } -func ExecuteWorkflowUI(cliConfig schema.CliConfiguration) (string, string, string, error) { - _, _, allWorkflows, err := ExecuteDescribeWorkflows(cliConfig) +func ExecuteWorkflowUI(atmosConfig schema.AtmosConfiguration) (string, string, string, error) { + _, _, allWorkflows, err := ExecuteDescribeWorkflows(atmosConfig) if err != nil { return "", "", "", err } diff --git a/internal/exec/yaml_func_exec.go b/internal/exec/yaml_func_exec.go index b33c7863a..b231b9da3 100644 --- a/internal/exec/yaml_func_exec.go +++ b/internal/exec/yaml_func_exec.go @@ -10,21 +10,21 @@ import ( ) func processTagExec( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, input string, currentStack string, ) any { - u.LogTrace(cliConfig, fmt.Sprintf("Executing Atmos YAML function: %s", input)) + u.LogTrace(atmosConfig, fmt.Sprintf("Executing Atmos YAML function: %s", input)) str, err := getStringAfterTag(input, config.AtmosYamlFuncExec) if err != nil { - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } - res, err := ExecuteShellAndReturnOutput(cliConfig, str, input, ".", nil, false) + res, err := ExecuteShellAndReturnOutput(atmosConfig, str, input, ".", nil, false) if err != nil { - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } var decoded any diff --git a/internal/exec/yaml_func_store.go b/internal/exec/yaml_func_store.go index df98cbc05..c5dd65ddb 100644 --- a/internal/exec/yaml_func_store.go +++ b/internal/exec/yaml_func_store.go @@ -9,32 +9,32 @@ import ( u "github.com/cloudposse/atmos/pkg/utils" ) -func processTagStore(cliConfig schema.CliConfiguration, input string, currentStack string) any { +func processTagStore(atmosConfig schema.AtmosConfiguration, input string, currentStack string) any { log.Debug("Executing Atmos YAML function store", "input", input) str, err := getStringAfterTag(input, u.AtmosYamlFuncStore) if err != nil { - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } parts := strings.Split(str, " ") if len(parts) != 2 { - u.LogErrorAndExit(cliConfig, fmt.Errorf("invalid Atmos Store YAML function execution:: %s\nexactly two parameters are required: store_name, key", input)) + u.LogErrorAndExit(atmosConfig, fmt.Errorf("invalid Atmos Store YAML function execution:: %s\nexactly two parameters are required: store_name, key", input)) } storeName := strings.TrimSpace(parts[0]) key := strings.TrimSpace(parts[1]) - store := cliConfig.Stores[storeName] + store := atmosConfig.Stores[storeName] if store == nil { - u.LogErrorAndExit(cliConfig, fmt.Errorf("invalid Atmos Store YAML function execution:: %s\nstore '%s' not found", input, storeName)) + u.LogErrorAndExit(atmosConfig, fmt.Errorf("invalid Atmos Store YAML function execution:: %s\nstore '%s' not found", input, storeName)) } value, err := store.Get(key) if err != nil { - u.LogErrorAndExit(cliConfig, fmt.Errorf("invalid Atmos Store YAML function execution:: %s\nkey '%s' not found in store '%s'", input, key, storeName)) + u.LogErrorAndExit(atmosConfig, fmt.Errorf("invalid Atmos Store YAML function execution:: %s\nkey '%s' not found in store '%s'", input, key, storeName)) } return value diff --git a/internal/exec/yaml_func_template.go b/internal/exec/yaml_func_template.go index 342e282f2..c0ab9046a 100644 --- a/internal/exec/yaml_func_template.go +++ b/internal/exec/yaml_func_template.go @@ -10,16 +10,16 @@ import ( ) func processTagTemplate( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, input string, currentStack string, ) any { - u.LogTrace(cliConfig, fmt.Sprintf("Executing Atmos YAML function: %s", input)) + u.LogTrace(atmosConfig, fmt.Sprintf("Executing Atmos YAML function: %s", input)) str, err := getStringAfterTag(input, config.AtmosYamlFuncTemplate) if err != nil { - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } var decoded any diff --git a/internal/exec/yaml_func_terraform_output.go b/internal/exec/yaml_func_terraform_output.go index 5eefa0226..375153d08 100644 --- a/internal/exec/yaml_func_terraform_output.go +++ b/internal/exec/yaml_func_terraform_output.go @@ -15,15 +15,15 @@ var ( ) func processTagTerraformOutput( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, input string, currentStack string, ) any { - u.LogTrace(cliConfig, fmt.Sprintf("Executing Atmos YAML function: %s", input)) + u.LogTrace(atmosConfig, fmt.Sprintf("Executing Atmos YAML function: %s", input)) str, err := getStringAfterTag(input, config.AtmosYamlFuncTerraformOutput) if err != nil { - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } var component string @@ -43,11 +43,11 @@ func processTagTerraformOutput( component = strings.TrimSpace(parts[0]) stack = currentStack output = strings.TrimSpace(parts[1]) - u.LogTrace(cliConfig, fmt.Sprintf("Atmos YAML function `%s` is called with two parameters 'component' and 'output'. "+ + u.LogTrace(atmosConfig, fmt.Sprintf("Atmos YAML function `%s` is called with two parameters 'component' and 'output'. "+ "Using the current stack '%s' as the 'stack' parameter", input, currentStack)) } else { err := fmt.Errorf("invalid number of arguments in the Atmos YAML function: %s", input) - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } stackSlug := fmt.Sprintf("%s-%s", stack, component) @@ -55,41 +55,41 @@ func processTagTerraformOutput( // If the result for the component in the stack already exists in the cache, return it cachedOutputs, found := terraformOutputFuncSyncMap.Load(stackSlug) if found && cachedOutputs != nil { - u.LogTrace(cliConfig, fmt.Sprintf("Found the result of the Atmos YAML function '!terraform.output %s %s %s' in the cache", component, stack, output)) - return getTerraformOutput(cliConfig, input, component, stack, cachedOutputs.(map[string]any), output) + u.LogTrace(atmosConfig, fmt.Sprintf("Found the result of the Atmos YAML function '!terraform.output %s %s %s' in the cache", component, stack, output)) + return getTerraformOutput(atmosConfig, input, component, stack, cachedOutputs.(map[string]any), output) } sections, err := ExecuteDescribeComponent(component, stack, true) if err != nil { - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } // Check if the component in the stack is configured with the 'static' remote state backend, // in which case get the `output` from the static remote state instead of executing `terraform output` remoteStateBackendStaticTypeOutputs, err := GetComponentRemoteStateBackendStaticType(sections) if err != nil { - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } if remoteStateBackendStaticTypeOutputs != nil { // Cache the result terraformOutputFuncSyncMap.Store(stackSlug, remoteStateBackendStaticTypeOutputs) - return getStaticRemoteStateOutput(cliConfig, input, component, stack, remoteStateBackendStaticTypeOutputs, output) + return getStaticRemoteStateOutput(atmosConfig, input, component, stack, remoteStateBackendStaticTypeOutputs, output) } else { // Execute `terraform output` - terraformOutputs, err := execTerraformOutput(cliConfig, component, stack, sections) + terraformOutputs, err := execTerraformOutput(atmosConfig, component, stack, sections) if err != nil { - u.LogErrorAndExit(cliConfig, err) + u.LogErrorAndExit(atmosConfig, err) } // Cache the result terraformOutputFuncSyncMap.Store(stackSlug, terraformOutputs) - return getTerraformOutput(cliConfig, input, component, stack, terraformOutputs, output) + return getTerraformOutput(atmosConfig, input, component, stack, terraformOutputs, output) } } func getTerraformOutput( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, funcDef string, component string, stack string, @@ -100,7 +100,7 @@ func getTerraformOutput( return outputs[output] } - u.LogErrorAndExit(cliConfig, fmt.Errorf("invalid Atmos YAML function: %s\nthe component '%s' in the stack '%s' does not have the output '%s'", + u.LogErrorAndExit(atmosConfig, fmt.Errorf("invalid Atmos YAML function: %s\nthe component '%s' in the stack '%s' does not have the output '%s'", funcDef, component, stack, @@ -111,7 +111,7 @@ func getTerraformOutput( } func getStaticRemoteStateOutput( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, funcDef string, component string, stack string, @@ -122,7 +122,7 @@ func getStaticRemoteStateOutput( return remoteStateSection[output] } - u.LogErrorAndExit(cliConfig, fmt.Errorf("invalid Atmos YAML function: %s\nthe component '%s' in the stack '%s' "+ + u.LogErrorAndExit(atmosConfig, fmt.Errorf("invalid Atmos YAML function: %s\nthe component '%s' in the stack '%s' "+ "is configured with the 'static' remote state backend, but the remote state backend does not have the output '%s'", funcDef, component, diff --git a/internal/exec/yaml_func_utils.go b/internal/exec/yaml_func_utils.go index 7604361ce..014821cc1 100644 --- a/internal/exec/yaml_func_utils.go +++ b/internal/exec/yaml_func_utils.go @@ -9,15 +9,15 @@ import ( ) func ProcessCustomYamlTags( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, input schema.AtmosSectionMapType, currentStack string, ) (schema.AtmosSectionMapType, error) { - return processNodes(cliConfig, input, currentStack), nil + return processNodes(atmosConfig, input, currentStack), nil } func processNodes( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, data map[string]any, currentStack string, ) map[string]any { @@ -27,7 +27,7 @@ func processNodes( recurse = func(node any) any { switch v := node.(type) { case string: - return processCustomTags(cliConfig, v, currentStack) + return processCustomTags(atmosConfig, v, currentStack) case map[string]any: newNestedMap := make(map[string]any) @@ -56,20 +56,20 @@ func processNodes( } func processCustomTags( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, input string, currentStack string, ) any { switch { case strings.HasPrefix(input, u.AtmosYamlFuncTemplate): - return processTagTemplate(cliConfig, input, currentStack) + return processTagTemplate(atmosConfig, input, currentStack) case strings.HasPrefix(input, u.AtmosYamlFuncExec): - return processTagExec(cliConfig, input, currentStack) + return processTagExec(atmosConfig, input, currentStack) case strings.HasPrefix(input, u.AtmosYamlFuncStore): - return processTagStore(cliConfig, input, currentStack) + return processTagStore(atmosConfig, input, currentStack) case strings.HasPrefix(input, u.AtmosYamlFuncTerraformOutput): - return processTagTerraformOutput(cliConfig, input, currentStack) + return processTagTerraformOutput(atmosConfig, input, currentStack) default: // If any other YAML explicit type (not currently supported by Atmos) is used, return it w/o processing return input diff --git a/main.go b/main.go index ca5d8ae86..3696f6341 100644 --- a/main.go +++ b/main.go @@ -9,6 +9,6 @@ import ( func main() { err := cmd.Execute() if err != nil { - u.LogErrorAndExit(schema.CliConfiguration{}, err) + u.LogErrorAndExit(schema.AtmosConfiguration{}, err) } } diff --git a/pkg/atlantis/atlantis_generate_repo_config_test.go b/pkg/atlantis/atlantis_generate_repo_config_test.go index 11f93d24a..13ed6e85e 100644 --- a/pkg/atlantis/atlantis_generate_repo_config_test.go +++ b/pkg/atlantis/atlantis_generate_repo_config_test.go @@ -12,13 +12,13 @@ import ( ) func TestAtlantisGenerateRepoConfig(t *testing.T) { - cliConfig, err := cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, true) + atmosConfig, err := cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, true) assert.Nil(t, err) - err = u.PrintAsYAML(cliConfig) + err = u.PrintAsYAML(atmosConfig) assert.Nil(t, err) - atlantisConfig := cliConfig.Integrations.Atlantis + atlantisConfig := atmosConfig.Integrations.Atlantis configTemplateName := "config-1" configTemplate := atlantisConfig.ConfigTemplates[configTemplateName] projectTemplateName := "project-1" @@ -42,11 +42,11 @@ func TestAtlantisGenerateRepoConfig(t *testing.T) { } func TestExecuteAtlantisGenerateRepoConfig(t *testing.T) { - cliConfig, err := cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, true) + atmosConfig, err := cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, true) assert.Nil(t, err) err = e.ExecuteAtlantisGenerateRepoConfig( - cliConfig, + atmosConfig, "/dev/stdout", "config-1", "project-1", @@ -58,11 +58,11 @@ func TestExecuteAtlantisGenerateRepoConfig(t *testing.T) { } func TestExecuteAtlantisGenerateRepoConfig2(t *testing.T) { - cliConfig, err := cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, true) + atmosConfig, err := cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, true) assert.Nil(t, err) err = e.ExecuteAtlantisGenerateRepoConfig( - cliConfig, + atmosConfig, "/dev/stdout", "", "", @@ -74,11 +74,11 @@ func TestExecuteAtlantisGenerateRepoConfig2(t *testing.T) { } func TestExecuteAtlantisGenerateRepoConfigAffectedOnly(t *testing.T) { - cliConfig, err := cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, true) + atmosConfig, err := cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, true) assert.Nil(t, err) err = e.ExecuteAtlantisGenerateRepoConfigAffectedOnly( - cliConfig, + atmosConfig, "/dev/stdout", "", "", diff --git a/pkg/aws/aws_eks_update_kubeconfig.go b/pkg/aws/aws_eks_update_kubeconfig.go index 9dc1750c2..8a20669a5 100644 --- a/pkg/aws/aws_eks_update_kubeconfig.go +++ b/pkg/aws/aws_eks_update_kubeconfig.go @@ -12,7 +12,7 @@ func ExecuteAwsEksUpdateKubeconfig(kubeconfigContext schema.AwsEksUpdateKubeconf err := e.ExecuteAwsEksUpdateKubeconfig(kubeconfigContext) if err != nil { - u.LogError(schema.CliConfiguration{}, err) + u.LogError(schema.AtmosConfiguration{}, err) return err } diff --git a/pkg/aws/aws_eks_update_kubeconfig_test.go b/pkg/aws/aws_eks_update_kubeconfig_test.go index bb20f838a..27d2f4427 100644 --- a/pkg/aws/aws_eks_update_kubeconfig_test.go +++ b/pkg/aws/aws_eks_update_kubeconfig_test.go @@ -2,9 +2,10 @@ package aws import ( "fmt" - "github.com/stretchr/testify/assert" "testing" + "github.com/stretchr/testify/assert" + cfg "github.com/cloudposse/atmos/pkg/config" "github.com/cloudposse/atmos/pkg/schema" u "github.com/cloudposse/atmos/pkg/utils" @@ -12,7 +13,7 @@ import ( func TestClusterNamePattern(t *testing.T) { // InitCliConfig finds and processes `atmos.yaml` CLI config - cliConfig, err := cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, true) + atmosConfig, err := cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, true) assert.Nil(t, err) // Define variables for a component in a stack @@ -29,7 +30,7 @@ func TestClusterNamePattern(t *testing.T) { // Build EKS cluster name using the `components.helmfile.cluster_name_pattern` config from `atmos.yaml` // cluster_name_pattern: "{namespace}-{tenant}-{environment}-{stage}-{attributes}-eks-cluster" - clusterName := cfg.ReplaceContextTokens(context, cliConfig.Components.Helmfile.ClusterNamePattern) + clusterName := cfg.ReplaceContextTokens(context, atmosConfig.Components.Helmfile.ClusterNamePattern) u.PrintMessage(fmt.Sprintf("Cluster name: %s", clusterName)) assert.Equal(t, "cp-plat-ue2-dev-blue-eks-cluster", clusterName) } diff --git a/pkg/component/component_processor.go b/pkg/component/component_processor.go index f49dbb121..b2c6db215 100644 --- a/pkg/component/component_processor.go +++ b/pkg/component/component_processor.go @@ -23,19 +23,19 @@ func ProcessComponentInStack( configAndStacksInfo.AtmosCliConfigPath = atmosCliConfigPath configAndStacksInfo.AtmosBasePath = atmosBasePath - cliConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) + atmosConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) if err != nil { - u.LogError(cliConfig, err) + u.LogError(atmosConfig, err) return nil, err } configAndStacksInfo.ComponentType = "terraform" - configAndStacksInfo, err = e.ProcessStacks(cliConfig, configAndStacksInfo, true, true) + configAndStacksInfo, err = e.ProcessStacks(atmosConfig, configAndStacksInfo, true, true) if err != nil { configAndStacksInfo.ComponentType = "helmfile" - configAndStacksInfo, err = e.ProcessStacks(cliConfig, configAndStacksInfo, true, true) + configAndStacksInfo, err = e.ProcessStacks(atmosConfig, configAndStacksInfo, true, true) if err != nil { - u.LogError(cliConfig, err) + u.LogError(atmosConfig, err) return nil, err } } @@ -59,21 +59,21 @@ func ProcessComponentFromContext( configAndStacksInfo.AtmosCliConfigPath = atmosCliConfigPath configAndStacksInfo.AtmosBasePath = atmosBasePath - cliConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) + atmosConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) if err != nil { - u.LogError(cliConfig, err) + u.LogError(atmosConfig, err) return nil, err } - if len(e.GetStackNamePattern(cliConfig)) < 1 { + if len(e.GetStackNamePattern(atmosConfig)) < 1 { er := errors.New("stack name pattern must be provided in 'stacks.name_pattern' CLI config or 'ATMOS_STACKS_NAME_PATTERN' ENV variable") - u.LogError(cliConfig, er) + u.LogError(atmosConfig, er) return nil, er } - stack, err := cfg.GetStackNameFromContextAndStackNamePattern(namespace, tenant, environment, stage, e.GetStackNamePattern(cliConfig)) + stack, err := cfg.GetStackNameFromContextAndStackNamePattern(namespace, tenant, environment, stage, e.GetStackNamePattern(atmosConfig)) if err != nil { - u.LogError(cliConfig, err) + u.LogError(atmosConfig, err) return nil, err } diff --git a/pkg/config/cache.go b/pkg/config/cache.go index 6833e67b5..cf70ab675 100644 --- a/pkg/config/cache.go +++ b/pkg/config/cache.go @@ -105,7 +105,7 @@ func ShouldCheckForUpdates(lastChecked int64, frequency string) bool { interval, err := parseFrequency(frequency) if err != nil { // Log warning and default to daily if we can’t parse - u.LogWarning(schema.CliConfiguration{}, fmt.Sprintf("Unsupported frequency '%s' encountered. Defaulting to daily.", frequency)) + u.LogWarning(schema.AtmosConfiguration{}, fmt.Sprintf("Unsupported frequency '%s' encountered. Defaulting to daily.", frequency)) interval = 86400 // daily } return now-lastChecked >= interval diff --git a/pkg/config/config.go b/pkg/config/config.go index 998a358b1..df60ff8d5 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -23,7 +23,7 @@ var ( "\nYou can download a sample config and adapt it to your requirements from " + "https://raw.githubusercontent.com/cloudposse/atmos/main/examples/quick-start-advanced/atmos.yaml") - defaultCliConfig = schema.CliConfiguration{ + defaultCliConfig = schema.AtmosConfiguration{ Default: true, BasePath: ".", Stacks: schema.Stacks{ @@ -94,15 +94,15 @@ var ( // InitCliConfig finds and merges CLI configurations in the following order: system dir, home dir, current dir, ENV vars, command-line arguments // https://dev.to/techschoolguru/load-config-from-file-environment-variables-in-golang-with-viper-2j2d // https://medium.com/@bnprashanth256/reading-configuration-files-and-environment-variables-in-go-golang-c2607f912b63 -func InitCliConfig(configAndStacksInfo schema.ConfigAndStacksInfo, processStacks bool) (schema.CliConfiguration, error) { - // cliConfig is loaded from the following locations (from lower to higher priority): +func InitCliConfig(configAndStacksInfo schema.ConfigAndStacksInfo, processStacks bool) (schema.AtmosConfiguration, error) { + // atmosConfig is loaded from the following locations (from lower to higher priority): // system dir (`/usr/local/etc/atmos` on Linux, `%LOCALAPPDATA%/atmos` on Windows) // home dir (~/.atmos) // current directory // ENV vars // Command-line arguments - var cliConfig schema.CliConfiguration + var atmosConfig schema.AtmosConfiguration var err error configFound := false var found bool @@ -133,9 +133,9 @@ func InitCliConfig(configAndStacksInfo schema.ConfigAndStacksInfo, processStacks if len(configFilePath1) > 0 { configFile1 := filepath.Join(configFilePath1, CliConfigFileName) - found, err = processConfigFile(cliConfig, configFile1, v) + found, err = processConfigFile(atmosConfig, configFile1, v) if err != nil { - return cliConfig, err + return atmosConfig, err } if found { configFound = true @@ -145,12 +145,12 @@ func InitCliConfig(configAndStacksInfo schema.ConfigAndStacksInfo, processStacks // Process config in user's HOME dir configFilePath2, err := homedir.Dir() if err != nil { - return cliConfig, err + return atmosConfig, err } configFile2 := filepath.Join(configFilePath2, ".atmos", CliConfigFileName) - found, err = processConfigFile(cliConfig, configFile2, v) + found, err = processConfigFile(atmosConfig, configFile2, v) if err != nil { - return cliConfig, err + return atmosConfig, err } if found { configFound = true @@ -159,12 +159,12 @@ func InitCliConfig(configAndStacksInfo schema.ConfigAndStacksInfo, processStacks // Process config in the current dir configFilePath3, err := os.Getwd() if err != nil { - return cliConfig, err + return atmosConfig, err } configFile3 := filepath.Join(configFilePath3, CliConfigFileName) - found, err = processConfigFile(cliConfig, configFile3, v) + found, err = processConfigFile(atmosConfig, configFile3, v) if err != nil { - return cliConfig, err + return atmosConfig, err } if found { configFound = true @@ -173,11 +173,11 @@ func InitCliConfig(configAndStacksInfo schema.ConfigAndStacksInfo, processStacks // Process config from the path in ENV var `ATMOS_CLI_CONFIG_PATH` configFilePath4 := os.Getenv("ATMOS_CLI_CONFIG_PATH") if len(configFilePath4) > 0 { - u.LogTrace(cliConfig, fmt.Sprintf("Found ENV var ATMOS_CLI_CONFIG_PATH=%s", configFilePath4)) + u.LogTrace(atmosConfig, fmt.Sprintf("Found ENV var ATMOS_CLI_CONFIG_PATH=%s", configFilePath4)) configFile4 := filepath.Join(configFilePath4, CliConfigFileName) - found, err = processConfigFile(cliConfig, configFile4, v) + found, err = processConfigFile(atmosConfig, configFile4, v) if err != nil { - return cliConfig, err + return atmosConfig, err } if found { configFound = true @@ -189,9 +189,9 @@ func InitCliConfig(configAndStacksInfo schema.ConfigAndStacksInfo, processStacks configFilePath5 := configAndStacksInfo.AtmosCliConfigPath if len(configFilePath5) > 0 { configFile5 := filepath.Join(configFilePath5, CliConfigFileName) - found, err = processConfigFile(cliConfig, configFile5, v) + found, err = processConfigFile(atmosConfig, configFile5, v) if err != nil { - return cliConfig, err + return atmosConfig, err } if found { configFound = true @@ -208,153 +208,153 @@ func InitCliConfig(configAndStacksInfo schema.ConfigAndStacksInfo, processStacks "Refer to https://atmos.tools/cli/configuration for details on how to configure 'atmos.yaml'.\n"+ "Using the default CLI config:\n\n", color.New(color.FgCyan)) - err = u.PrintAsYAMLToFileDescriptor(cliConfig, defaultCliConfig) + err = u.PrintAsYAMLToFileDescriptor(atmosConfig, defaultCliConfig) if err != nil { - return cliConfig, err + return atmosConfig, err } fmt.Println() } j, err := json.Marshal(defaultCliConfig) if err != nil { - return cliConfig, err + return atmosConfig, err } reader := bytes.NewReader(j) err = v.MergeConfig(reader) if err != nil { - return cliConfig, err + return atmosConfig, err } } // https://gist.github.com/chazcheadle/45bf85b793dea2b71bd05ebaa3c28644 // https://sagikazarmark.hu/blog/decoding-custom-formats-with-viper/ - err = v.Unmarshal(&cliConfig) + err = v.Unmarshal(&atmosConfig) if err != nil { - return cliConfig, err + return atmosConfig, err } // Process ENV vars - err = processEnvVars(&cliConfig) + err = processEnvVars(&atmosConfig) if err != nil { - return cliConfig, err + return atmosConfig, err } // Process command-line args - err = processCommandLineArgs(&cliConfig, configAndStacksInfo) + err = processCommandLineArgs(&atmosConfig, configAndStacksInfo) if err != nil { - return cliConfig, err + return atmosConfig, err } // Process stores config - err = processStoreConfig(&cliConfig) + err = processStoreConfig(&atmosConfig) if err != nil { - return cliConfig, err + return atmosConfig, err } // Process the base path specified in the Terraform provider (which calls into the atmos code) // This overrides all other atmos base path configs (`atmos.yaml`, ENV var `ATMOS_BASE_PATH`) if configAndStacksInfo.AtmosBasePath != "" { - cliConfig.BasePath = configAndStacksInfo.AtmosBasePath + atmosConfig.BasePath = configAndStacksInfo.AtmosBasePath } // After unmarshalling, ensure AppendUserAgent is set if still empty - if cliConfig.Components.Terraform.AppendUserAgent == "" { - cliConfig.Components.Terraform.AppendUserAgent = fmt.Sprintf("Atmos/%s (Cloud Posse; +https://atmos.tools)", version.Version) + if atmosConfig.Components.Terraform.AppendUserAgent == "" { + atmosConfig.Components.Terraform.AppendUserAgent = fmt.Sprintf("Atmos/%s (Cloud Posse; +https://atmos.tools)", version.Version) } // Check config - err = checkConfig(cliConfig) + err = checkConfig(atmosConfig) if err != nil { - return cliConfig, err + return atmosConfig, err } // Convert stacks base path to absolute path - stacksBasePath := filepath.Join(cliConfig.BasePath, cliConfig.Stacks.BasePath) + stacksBasePath := filepath.Join(atmosConfig.BasePath, atmosConfig.Stacks.BasePath) stacksBaseAbsPath, err := filepath.Abs(stacksBasePath) if err != nil { - return cliConfig, err + return atmosConfig, err } - cliConfig.StacksBaseAbsolutePath = stacksBaseAbsPath + atmosConfig.StacksBaseAbsolutePath = stacksBaseAbsPath // Convert the included stack paths to absolute paths - includeStackAbsPaths, err := u.JoinAbsolutePathWithPaths(stacksBaseAbsPath, cliConfig.Stacks.IncludedPaths) + includeStackAbsPaths, err := u.JoinAbsolutePathWithPaths(stacksBaseAbsPath, atmosConfig.Stacks.IncludedPaths) if err != nil { - return cliConfig, err + return atmosConfig, err } - cliConfig.IncludeStackAbsolutePaths = includeStackAbsPaths + atmosConfig.IncludeStackAbsolutePaths = includeStackAbsPaths // Convert the excluded stack paths to absolute paths - excludeStackAbsPaths, err := u.JoinAbsolutePathWithPaths(stacksBaseAbsPath, cliConfig.Stacks.ExcludedPaths) + excludeStackAbsPaths, err := u.JoinAbsolutePathWithPaths(stacksBaseAbsPath, atmosConfig.Stacks.ExcludedPaths) if err != nil { - return cliConfig, err + return atmosConfig, err } - cliConfig.ExcludeStackAbsolutePaths = excludeStackAbsPaths + atmosConfig.ExcludeStackAbsolutePaths = excludeStackAbsPaths // Convert terraform dir to absolute path - terraformBasePath := filepath.Join(cliConfig.BasePath, cliConfig.Components.Terraform.BasePath) + terraformBasePath := filepath.Join(atmosConfig.BasePath, atmosConfig.Components.Terraform.BasePath) terraformDirAbsPath, err := filepath.Abs(terraformBasePath) if err != nil { - return cliConfig, err + return atmosConfig, err } - cliConfig.TerraformDirAbsolutePath = terraformDirAbsPath + atmosConfig.TerraformDirAbsolutePath = terraformDirAbsPath // Convert helmfile dir to absolute path - helmfileBasePath := filepath.Join(cliConfig.BasePath, cliConfig.Components.Helmfile.BasePath) + helmfileBasePath := filepath.Join(atmosConfig.BasePath, atmosConfig.Components.Helmfile.BasePath) helmfileDirAbsPath, err := filepath.Abs(helmfileBasePath) if err != nil { - return cliConfig, err + return atmosConfig, err } - cliConfig.HelmfileDirAbsolutePath = helmfileDirAbsPath + atmosConfig.HelmfileDirAbsolutePath = helmfileDirAbsPath if processStacks { // If the specified stack name is a logical name, find all stack manifests in the provided paths stackConfigFilesAbsolutePaths, stackConfigFilesRelativePaths, stackIsPhysicalPath, err := FindAllStackConfigsInPathsForStack( - cliConfig, + atmosConfig, configAndStacksInfo.Stack, includeStackAbsPaths, excludeStackAbsPaths, ) if err != nil { - return cliConfig, err + return atmosConfig, err } if len(stackConfigFilesAbsolutePaths) < 1 { j, err := u.ConvertToYAML(includeStackAbsPaths) if err != nil { - return cliConfig, err + return atmosConfig, err } errorMessage := fmt.Sprintf("\nno stack manifests found in the provided "+ "paths:\n%s\n\nCheck if `base_path`, 'stacks.base_path', 'stacks.included_paths' and 'stacks.excluded_paths' are correctly set in CLI config "+ "files or ENV vars.", j) - return cliConfig, errors.New(errorMessage) + return atmosConfig, errors.New(errorMessage) } - cliConfig.StackConfigFilesAbsolutePaths = stackConfigFilesAbsolutePaths - cliConfig.StackConfigFilesRelativePaths = stackConfigFilesRelativePaths + atmosConfig.StackConfigFilesAbsolutePaths = stackConfigFilesAbsolutePaths + atmosConfig.StackConfigFilesRelativePaths = stackConfigFilesRelativePaths if stackIsPhysicalPath { - u.LogTrace(cliConfig, fmt.Sprintf("\nThe stack '%s' matches the stack manifest %s\n", + u.LogTrace(atmosConfig, fmt.Sprintf("\nThe stack '%s' matches the stack manifest %s\n", configAndStacksInfo.Stack, stackConfigFilesRelativePaths[0]), ) - cliConfig.StackType = "Directory" + atmosConfig.StackType = "Directory" } else { // The stack is a logical name - cliConfig.StackType = "Logical" + atmosConfig.StackType = "Logical" } } - cliConfig.Initialized = true - return cliConfig, nil + atmosConfig.Initialized = true + return atmosConfig, nil } // https://github.com/NCAR/go-figure // https://github.com/spf13/viper/issues/181 // https://medium.com/@bnprashanth256/reading-configuration-files-and-environment-variables-in-go-golang-c2607f912b63 func processConfigFile( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, path string, v *viper.Viper, ) (bool, error) { @@ -371,7 +371,7 @@ func processConfigFile( defer func(reader *os.File) { err := reader.Close() if err != nil { - u.LogWarning(cliConfig, fmt.Sprintf("error closing file '"+configPath+"'. "+err.Error())) + u.LogWarning(atmosConfig, fmt.Sprintf("error closing file '"+configPath+"'. "+err.Error())) } }(reader) diff --git a/pkg/config/utils.go b/pkg/config/utils.go index 38b530b95..4fb525d78 100644 --- a/pkg/config/utils.go +++ b/pkg/config/utils.go @@ -16,7 +16,7 @@ import ( // FindAllStackConfigsInPathsForStack finds all stack manifests in the paths specified by globs for the provided stack func FindAllStackConfigsInPathsForStack( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, stack string, includeStackPaths []string, excludeStackPaths []string, @@ -51,8 +51,8 @@ func FindAllStackConfigsInPathsForStack( if len(allMatches) == 0 { _, err := u.GetGlobMatches(patterns[0]) if err != nil { - if cliConfig.Logs.Level == u.LogLevelTrace { - y, _ := u.ConvertToYAML(cliConfig) + if atmosConfig.Logs.Level == u.LogLevelTrace { + y, _ := u.ConvertToYAML(atmosConfig) return nil, nil, false, fmt.Errorf("%v\n\n\nCLI config:\n\n%v", err, y) } return nil, nil, false, err @@ -64,7 +64,7 @@ func FindAllStackConfigsInPathsForStack( // Process all matches found for _, matchedFileAbsolutePath := range allMatches { - matchedFileRelativePath := u.TrimBasePathFromPath(cliConfig.StacksBaseAbsolutePath+"/", matchedFileAbsolutePath) + matchedFileRelativePath := u.TrimBasePathFromPath(atmosConfig.StacksBaseAbsolutePath+"/", matchedFileAbsolutePath) // Check if the provided stack matches a file in the config folders (excluding the files from `excludeStackPaths`) stackMatch := matchesStackFilePattern(matchedFileAbsolutePath, stack) @@ -115,7 +115,7 @@ func FindAllStackConfigsInPathsForStack( // FindAllStackConfigsInPaths finds all stack manifests in the paths specified by globs func FindAllStackConfigsInPaths( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, includeStackPaths []string, excludeStackPaths []string, ) ([]string, []string, error) { @@ -147,8 +147,8 @@ func FindAllStackConfigsInPaths( if len(allMatches) == 0 { _, err := u.GetGlobMatches(patterns[0]) if err != nil { - if cliConfig.Logs.Level == u.LogLevelTrace { - y, _ := u.ConvertToYAML(cliConfig) + if atmosConfig.Logs.Level == u.LogLevelTrace { + y, _ := u.ConvertToYAML(atmosConfig) return nil, nil, fmt.Errorf("%v\n\n\nCLI config:\n\n%v", err, y) } return nil, nil, err @@ -160,7 +160,7 @@ func FindAllStackConfigsInPaths( // Process all matches found for _, matchedFileAbsolutePath := range allMatches { - matchedFileRelativePath := u.TrimBasePathFromPath(cliConfig.StacksBaseAbsolutePath+"/", matchedFileAbsolutePath) + matchedFileRelativePath := u.TrimBasePathFromPath(atmosConfig.StacksBaseAbsolutePath+"/", matchedFileAbsolutePath) include := true for _, excludePath := range excludeStackPaths { @@ -184,319 +184,319 @@ func FindAllStackConfigsInPaths( return absolutePaths, relativePaths, nil } -func processEnvVars(cliConfig *schema.CliConfiguration) error { +func processEnvVars(atmosConfig *schema.AtmosConfiguration) error { basePath := os.Getenv("ATMOS_BASE_PATH") if len(basePath) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_BASE_PATH=%s", basePath)) - cliConfig.BasePath = basePath + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_BASE_PATH=%s", basePath)) + atmosConfig.BasePath = basePath } vendorBasePath := os.Getenv("ATMOS_VENDOR_BASE_PATH") if len(vendorBasePath) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_VENDOR_BASE_PATH=%s", vendorBasePath)) - cliConfig.Vendor.BasePath = vendorBasePath + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_VENDOR_BASE_PATH=%s", vendorBasePath)) + atmosConfig.Vendor.BasePath = vendorBasePath } stacksBasePath := os.Getenv("ATMOS_STACKS_BASE_PATH") if len(stacksBasePath) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_STACKS_BASE_PATH=%s", stacksBasePath)) - cliConfig.Stacks.BasePath = stacksBasePath + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_STACKS_BASE_PATH=%s", stacksBasePath)) + atmosConfig.Stacks.BasePath = stacksBasePath } stacksIncludedPaths := os.Getenv("ATMOS_STACKS_INCLUDED_PATHS") if len(stacksIncludedPaths) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_STACKS_INCLUDED_PATHS=%s", stacksIncludedPaths)) - cliConfig.Stacks.IncludedPaths = strings.Split(stacksIncludedPaths, ",") + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_STACKS_INCLUDED_PATHS=%s", stacksIncludedPaths)) + atmosConfig.Stacks.IncludedPaths = strings.Split(stacksIncludedPaths, ",") } stacksExcludedPaths := os.Getenv("ATMOS_STACKS_EXCLUDED_PATHS") if len(stacksExcludedPaths) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_STACKS_EXCLUDED_PATHS=%s", stacksExcludedPaths)) - cliConfig.Stacks.ExcludedPaths = strings.Split(stacksExcludedPaths, ",") + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_STACKS_EXCLUDED_PATHS=%s", stacksExcludedPaths)) + atmosConfig.Stacks.ExcludedPaths = strings.Split(stacksExcludedPaths, ",") } stacksNamePattern := os.Getenv("ATMOS_STACKS_NAME_PATTERN") if len(stacksNamePattern) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_STACKS_NAME_PATTERN=%s", stacksNamePattern)) - cliConfig.Stacks.NamePattern = stacksNamePattern + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_STACKS_NAME_PATTERN=%s", stacksNamePattern)) + atmosConfig.Stacks.NamePattern = stacksNamePattern } stacksNameTemplate := os.Getenv("ATMOS_STACKS_NAME_TEMPLATE") if len(stacksNameTemplate) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_STACKS_NAME_TEMPLATE=%s", stacksNameTemplate)) - cliConfig.Stacks.NameTemplate = stacksNameTemplate + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_STACKS_NAME_TEMPLATE=%s", stacksNameTemplate)) + atmosConfig.Stacks.NameTemplate = stacksNameTemplate } componentsTerraformCommand := os.Getenv("ATMOS_COMPONENTS_TERRAFORM_COMMAND") if len(componentsTerraformCommand) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_TERRAFORM_COMMAND=%s", componentsTerraformCommand)) - cliConfig.Components.Terraform.Command = componentsTerraformCommand + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_TERRAFORM_COMMAND=%s", componentsTerraformCommand)) + atmosConfig.Components.Terraform.Command = componentsTerraformCommand } componentsTerraformBasePath := os.Getenv("ATMOS_COMPONENTS_TERRAFORM_BASE_PATH") if len(componentsTerraformBasePath) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_TERRAFORM_BASE_PATH=%s", componentsTerraformBasePath)) - cliConfig.Components.Terraform.BasePath = componentsTerraformBasePath + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_TERRAFORM_BASE_PATH=%s", componentsTerraformBasePath)) + atmosConfig.Components.Terraform.BasePath = componentsTerraformBasePath } componentsTerraformApplyAutoApprove := os.Getenv("ATMOS_COMPONENTS_TERRAFORM_APPLY_AUTO_APPROVE") if len(componentsTerraformApplyAutoApprove) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_TERRAFORM_APPLY_AUTO_APPROVE=%s", componentsTerraformApplyAutoApprove)) + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_TERRAFORM_APPLY_AUTO_APPROVE=%s", componentsTerraformApplyAutoApprove)) applyAutoApproveBool, err := strconv.ParseBool(componentsTerraformApplyAutoApprove) if err != nil { return err } - cliConfig.Components.Terraform.ApplyAutoApprove = applyAutoApproveBool + atmosConfig.Components.Terraform.ApplyAutoApprove = applyAutoApproveBool } componentsTerraformDeployRunInit := os.Getenv("ATMOS_COMPONENTS_TERRAFORM_DEPLOY_RUN_INIT") if len(componentsTerraformDeployRunInit) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_TERRAFORM_DEPLOY_RUN_INIT=%s", componentsTerraformDeployRunInit)) + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_TERRAFORM_DEPLOY_RUN_INIT=%s", componentsTerraformDeployRunInit)) deployRunInitBool, err := strconv.ParseBool(componentsTerraformDeployRunInit) if err != nil { return err } - cliConfig.Components.Terraform.DeployRunInit = deployRunInitBool + atmosConfig.Components.Terraform.DeployRunInit = deployRunInitBool } componentsInitRunReconfigure := os.Getenv("ATMOS_COMPONENTS_TERRAFORM_INIT_RUN_RECONFIGURE") if len(componentsInitRunReconfigure) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_TERRAFORM_INIT_RUN_RECONFIGURE=%s", componentsInitRunReconfigure)) + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_TERRAFORM_INIT_RUN_RECONFIGURE=%s", componentsInitRunReconfigure)) initRunReconfigureBool, err := strconv.ParseBool(componentsInitRunReconfigure) if err != nil { return err } - cliConfig.Components.Terraform.InitRunReconfigure = initRunReconfigureBool + atmosConfig.Components.Terraform.InitRunReconfigure = initRunReconfigureBool } componentsTerraformAutoGenerateBackendFile := os.Getenv("ATMOS_COMPONENTS_TERRAFORM_AUTO_GENERATE_BACKEND_FILE") if len(componentsTerraformAutoGenerateBackendFile) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_TERRAFORM_AUTO_GENERATE_BACKEND_FILE=%s", componentsTerraformAutoGenerateBackendFile)) + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_TERRAFORM_AUTO_GENERATE_BACKEND_FILE=%s", componentsTerraformAutoGenerateBackendFile)) componentsTerraformAutoGenerateBackendFileBool, err := strconv.ParseBool(componentsTerraformAutoGenerateBackendFile) if err != nil { return err } - cliConfig.Components.Terraform.AutoGenerateBackendFile = componentsTerraformAutoGenerateBackendFileBool + atmosConfig.Components.Terraform.AutoGenerateBackendFile = componentsTerraformAutoGenerateBackendFileBool } componentsHelmfileCommand := os.Getenv("ATMOS_COMPONENTS_HELMFILE_COMMAND") if len(componentsHelmfileCommand) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_HELMFILE_COMMAND=%s", componentsHelmfileCommand)) - cliConfig.Components.Helmfile.Command = componentsHelmfileCommand + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_HELMFILE_COMMAND=%s", componentsHelmfileCommand)) + atmosConfig.Components.Helmfile.Command = componentsHelmfileCommand } componentsHelmfileBasePath := os.Getenv("ATMOS_COMPONENTS_HELMFILE_BASE_PATH") if len(componentsHelmfileBasePath) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_HELMFILE_BASE_PATH=%s", componentsHelmfileBasePath)) - cliConfig.Components.Helmfile.BasePath = componentsHelmfileBasePath + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_HELMFILE_BASE_PATH=%s", componentsHelmfileBasePath)) + atmosConfig.Components.Helmfile.BasePath = componentsHelmfileBasePath } componentsHelmfileUseEKS := os.Getenv("ATMOS_COMPONENTS_HELMFILE_USE_EKS") if len(componentsHelmfileUseEKS) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_HELMFILE_USE_EKS=%s", componentsHelmfileUseEKS)) + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_HELMFILE_USE_EKS=%s", componentsHelmfileUseEKS)) useEKSBool, err := strconv.ParseBool(componentsHelmfileUseEKS) if err != nil { return err } - cliConfig.Components.Helmfile.UseEKS = useEKSBool + atmosConfig.Components.Helmfile.UseEKS = useEKSBool } componentsHelmfileKubeconfigPath := os.Getenv("ATMOS_COMPONENTS_HELMFILE_KUBECONFIG_PATH") if len(componentsHelmfileKubeconfigPath) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_HELMFILE_KUBECONFIG_PATH=%s", componentsHelmfileKubeconfigPath)) - cliConfig.Components.Helmfile.KubeconfigPath = componentsHelmfileKubeconfigPath + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_HELMFILE_KUBECONFIG_PATH=%s", componentsHelmfileKubeconfigPath)) + atmosConfig.Components.Helmfile.KubeconfigPath = componentsHelmfileKubeconfigPath } componentsHelmfileHelmAwsProfilePattern := os.Getenv("ATMOS_COMPONENTS_HELMFILE_HELM_AWS_PROFILE_PATTERN") if len(componentsHelmfileHelmAwsProfilePattern) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_HELMFILE_HELM_AWS_PROFILE_PATTERN=%s", componentsHelmfileHelmAwsProfilePattern)) - cliConfig.Components.Helmfile.HelmAwsProfilePattern = componentsHelmfileHelmAwsProfilePattern + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_HELMFILE_HELM_AWS_PROFILE_PATTERN=%s", componentsHelmfileHelmAwsProfilePattern)) + atmosConfig.Components.Helmfile.HelmAwsProfilePattern = componentsHelmfileHelmAwsProfilePattern } componentsHelmfileClusterNamePattern := os.Getenv("ATMOS_COMPONENTS_HELMFILE_CLUSTER_NAME_PATTERN") if len(componentsHelmfileClusterNamePattern) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_HELMFILE_CLUSTER_NAME_PATTERN=%s", componentsHelmfileClusterNamePattern)) - cliConfig.Components.Helmfile.ClusterNamePattern = componentsHelmfileClusterNamePattern + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_HELMFILE_CLUSTER_NAME_PATTERN=%s", componentsHelmfileClusterNamePattern)) + atmosConfig.Components.Helmfile.ClusterNamePattern = componentsHelmfileClusterNamePattern } workflowsBasePath := os.Getenv("ATMOS_WORKFLOWS_BASE_PATH") if len(workflowsBasePath) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_WORKFLOWS_BASE_PATH=%s", workflowsBasePath)) - cliConfig.Workflows.BasePath = workflowsBasePath + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_WORKFLOWS_BASE_PATH=%s", workflowsBasePath)) + atmosConfig.Workflows.BasePath = workflowsBasePath } jsonschemaBasePath := os.Getenv("ATMOS_SCHEMAS_JSONSCHEMA_BASE_PATH") if len(jsonschemaBasePath) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_SCHEMAS_JSONSCHEMA_BASE_PATH=%s", jsonschemaBasePath)) - cliConfig.Schemas.JsonSchema.BasePath = jsonschemaBasePath + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_SCHEMAS_JSONSCHEMA_BASE_PATH=%s", jsonschemaBasePath)) + atmosConfig.Schemas.JsonSchema.BasePath = jsonschemaBasePath } opaBasePath := os.Getenv("ATMOS_SCHEMAS_OPA_BASE_PATH") if len(opaBasePath) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_SCHEMAS_OPA_BASE_PATH=%s", opaBasePath)) - cliConfig.Schemas.Opa.BasePath = opaBasePath + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_SCHEMAS_OPA_BASE_PATH=%s", opaBasePath)) + atmosConfig.Schemas.Opa.BasePath = opaBasePath } cueBasePath := os.Getenv("ATMOS_SCHEMAS_CUE_BASE_PATH") if len(cueBasePath) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_SCHEMAS_CUE_BASE_PATH=%s", cueBasePath)) - cliConfig.Schemas.Cue.BasePath = cueBasePath + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_SCHEMAS_CUE_BASE_PATH=%s", cueBasePath)) + atmosConfig.Schemas.Cue.BasePath = cueBasePath } atmosManifestJsonSchemaPath := os.Getenv("ATMOS_SCHEMAS_ATMOS_MANIFEST") if len(atmosManifestJsonSchemaPath) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_SCHEMAS_ATMOS_MANIFEST=%s", atmosManifestJsonSchemaPath)) - cliConfig.Schemas.Atmos.Manifest = atmosManifestJsonSchemaPath + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_SCHEMAS_ATMOS_MANIFEST=%s", atmosManifestJsonSchemaPath)) + atmosConfig.Schemas.Atmos.Manifest = atmosManifestJsonSchemaPath } logsFile := os.Getenv("ATMOS_LOGS_FILE") if len(logsFile) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_LOGS_FILE=%s", logsFile)) - cliConfig.Logs.File = logsFile + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_LOGS_FILE=%s", logsFile)) + atmosConfig.Logs.File = logsFile } logsLevel := os.Getenv("ATMOS_LOGS_LEVEL") if len(logsLevel) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_LOGS_LEVEL=%s", logsLevel)) - cliConfig.Logs.Level = logsLevel + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_LOGS_LEVEL=%s", logsLevel)) + atmosConfig.Logs.Level = logsLevel } tfAppendUserAgent := os.Getenv("ATMOS_COMPONENTS_TERRAFORM_APPEND_USER_AGENT") if len(tfAppendUserAgent) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_TERRAFORM_APPEND_USER_AGENT=%s", tfAppendUserAgent)) - cliConfig.Components.Terraform.AppendUserAgent = tfAppendUserAgent + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_TERRAFORM_APPEND_USER_AGENT=%s", tfAppendUserAgent)) + atmosConfig.Components.Terraform.AppendUserAgent = tfAppendUserAgent } listMergeStrategy := os.Getenv("ATMOS_SETTINGS_LIST_MERGE_STRATEGY") if len(listMergeStrategy) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_SETTINGS_LIST_MERGE_STRATEGY=%s", listMergeStrategy)) - cliConfig.Settings.ListMergeStrategy = listMergeStrategy + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_SETTINGS_LIST_MERGE_STRATEGY=%s", listMergeStrategy)) + atmosConfig.Settings.ListMergeStrategy = listMergeStrategy } versionEnabled := os.Getenv("ATMOS_VERSION_CHECK_ENABLED") if len(versionEnabled) > 0 { - u.LogTrace(*cliConfig, fmt.Sprintf("Found ENV var ATMOS_VERSION_CHECK_ENABLED=%s", versionEnabled)) + u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_VERSION_CHECK_ENABLED=%s", versionEnabled)) enabled, err := strconv.ParseBool(versionEnabled) if err != nil { - u.LogWarning(*cliConfig, fmt.Sprintf("Invalid boolean value '%s' for ATMOS_VERSION_CHECK_ENABLED; using default.", versionEnabled)) + u.LogWarning(*atmosConfig, fmt.Sprintf("Invalid boolean value '%s' for ATMOS_VERSION_CHECK_ENABLED; using default.", versionEnabled)) } else { - cliConfig.Version.Check.Enabled = enabled + atmosConfig.Version.Check.Enabled = enabled } } return nil } -func checkConfig(cliConfig schema.CliConfiguration) error { - if len(cliConfig.Stacks.BasePath) < 1 { +func checkConfig(atmosConfig schema.AtmosConfiguration) error { + if len(atmosConfig.Stacks.BasePath) < 1 { return errors.New("stack base path must be provided in 'stacks.base_path' config or ATMOS_STACKS_BASE_PATH' ENV variable") } - if len(cliConfig.Stacks.IncludedPaths) < 1 { + if len(atmosConfig.Stacks.IncludedPaths) < 1 { return errors.New("at least one path must be provided in 'stacks.included_paths' config or ATMOS_STACKS_INCLUDED_PATHS' ENV variable") } return nil } -func processCommandLineArgs(cliConfig *schema.CliConfiguration, configAndStacksInfo schema.ConfigAndStacksInfo) error { +func processCommandLineArgs(atmosConfig *schema.AtmosConfiguration, configAndStacksInfo schema.ConfigAndStacksInfo) error { if len(configAndStacksInfo.BasePath) > 0 { - cliConfig.BasePath = configAndStacksInfo.BasePath - u.LogTrace(*cliConfig, fmt.Sprintf("Using command line argument '%s' as base path for stacks and components", configAndStacksInfo.BasePath)) + atmosConfig.BasePath = configAndStacksInfo.BasePath + u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s' as base path for stacks and components", configAndStacksInfo.BasePath)) } if len(configAndStacksInfo.TerraformCommand) > 0 { - cliConfig.Components.Terraform.Command = configAndStacksInfo.TerraformCommand - u.LogTrace(*cliConfig, fmt.Sprintf("Using command line argument '%s' as terraform executable", configAndStacksInfo.TerraformCommand)) + atmosConfig.Components.Terraform.Command = configAndStacksInfo.TerraformCommand + u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s' as terraform executable", configAndStacksInfo.TerraformCommand)) } if len(configAndStacksInfo.TerraformDir) > 0 { - cliConfig.Components.Terraform.BasePath = configAndStacksInfo.TerraformDir - u.LogTrace(*cliConfig, fmt.Sprintf("Using command line argument '%s' as terraform directory", configAndStacksInfo.TerraformDir)) + atmosConfig.Components.Terraform.BasePath = configAndStacksInfo.TerraformDir + u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s' as terraform directory", configAndStacksInfo.TerraformDir)) } if len(configAndStacksInfo.HelmfileCommand) > 0 { - cliConfig.Components.Helmfile.Command = configAndStacksInfo.HelmfileCommand - u.LogTrace(*cliConfig, fmt.Sprintf("Using command line argument '%s' as helmfile executable", configAndStacksInfo.HelmfileCommand)) + atmosConfig.Components.Helmfile.Command = configAndStacksInfo.HelmfileCommand + u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s' as helmfile executable", configAndStacksInfo.HelmfileCommand)) } if len(configAndStacksInfo.HelmfileDir) > 0 { - cliConfig.Components.Helmfile.BasePath = configAndStacksInfo.HelmfileDir - u.LogTrace(*cliConfig, fmt.Sprintf("Using command line argument '%s' as helmfile directory", configAndStacksInfo.HelmfileDir)) + atmosConfig.Components.Helmfile.BasePath = configAndStacksInfo.HelmfileDir + u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s' as helmfile directory", configAndStacksInfo.HelmfileDir)) } if len(configAndStacksInfo.ConfigDir) > 0 { - cliConfig.Stacks.BasePath = configAndStacksInfo.ConfigDir - u.LogTrace(*cliConfig, fmt.Sprintf("Using command line argument '%s' as stacks directory", configAndStacksInfo.ConfigDir)) + atmosConfig.Stacks.BasePath = configAndStacksInfo.ConfigDir + u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s' as stacks directory", configAndStacksInfo.ConfigDir)) } if len(configAndStacksInfo.StacksDir) > 0 { - cliConfig.Stacks.BasePath = configAndStacksInfo.StacksDir - u.LogTrace(*cliConfig, fmt.Sprintf("Using command line argument '%s' as stacks directory", configAndStacksInfo.StacksDir)) + atmosConfig.Stacks.BasePath = configAndStacksInfo.StacksDir + u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s' as stacks directory", configAndStacksInfo.StacksDir)) } if len(configAndStacksInfo.DeployRunInit) > 0 { deployRunInitBool, err := strconv.ParseBool(configAndStacksInfo.DeployRunInit) if err != nil { return err } - cliConfig.Components.Terraform.DeployRunInit = deployRunInitBool - u.LogTrace(*cliConfig, fmt.Sprintf("Using command line argument '%s=%s'", DeployRunInitFlag, configAndStacksInfo.DeployRunInit)) + atmosConfig.Components.Terraform.DeployRunInit = deployRunInitBool + u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s=%s'", DeployRunInitFlag, configAndStacksInfo.DeployRunInit)) } if len(configAndStacksInfo.AutoGenerateBackendFile) > 0 { autoGenerateBackendFileBool, err := strconv.ParseBool(configAndStacksInfo.AutoGenerateBackendFile) if err != nil { return err } - cliConfig.Components.Terraform.AutoGenerateBackendFile = autoGenerateBackendFileBool - u.LogTrace(*cliConfig, fmt.Sprintf("Using command line argument '%s=%s'", AutoGenerateBackendFileFlag, configAndStacksInfo.AutoGenerateBackendFile)) + atmosConfig.Components.Terraform.AutoGenerateBackendFile = autoGenerateBackendFileBool + u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s=%s'", AutoGenerateBackendFileFlag, configAndStacksInfo.AutoGenerateBackendFile)) } if len(configAndStacksInfo.WorkflowsDir) > 0 { - cliConfig.Workflows.BasePath = configAndStacksInfo.WorkflowsDir - u.LogTrace(*cliConfig, fmt.Sprintf("Using command line argument '%s' as workflows directory", configAndStacksInfo.WorkflowsDir)) + atmosConfig.Workflows.BasePath = configAndStacksInfo.WorkflowsDir + u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s' as workflows directory", configAndStacksInfo.WorkflowsDir)) } if len(configAndStacksInfo.InitRunReconfigure) > 0 { initRunReconfigureBool, err := strconv.ParseBool(configAndStacksInfo.InitRunReconfigure) if err != nil { return err } - cliConfig.Components.Terraform.InitRunReconfigure = initRunReconfigureBool - u.LogTrace(*cliConfig, fmt.Sprintf("Using command line argument '%s=%s'", InitRunReconfigure, configAndStacksInfo.InitRunReconfigure)) + atmosConfig.Components.Terraform.InitRunReconfigure = initRunReconfigureBool + u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s=%s'", InitRunReconfigure, configAndStacksInfo.InitRunReconfigure)) } if len(configAndStacksInfo.JsonSchemaDir) > 0 { - cliConfig.Schemas.JsonSchema.BasePath = configAndStacksInfo.JsonSchemaDir - u.LogTrace(*cliConfig, fmt.Sprintf("Using command line argument '%s' as JsonSchema schemas directory", configAndStacksInfo.JsonSchemaDir)) + atmosConfig.Schemas.JsonSchema.BasePath = configAndStacksInfo.JsonSchemaDir + u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s' as JsonSchema schemas directory", configAndStacksInfo.JsonSchemaDir)) } if len(configAndStacksInfo.OpaDir) > 0 { - cliConfig.Schemas.Opa.BasePath = configAndStacksInfo.OpaDir - u.LogTrace(*cliConfig, fmt.Sprintf("Using command line argument '%s' as OPA schemas directory", configAndStacksInfo.OpaDir)) + atmosConfig.Schemas.Opa.BasePath = configAndStacksInfo.OpaDir + u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s' as OPA schemas directory", configAndStacksInfo.OpaDir)) } if len(configAndStacksInfo.CueDir) > 0 { - cliConfig.Schemas.Cue.BasePath = configAndStacksInfo.CueDir - u.LogTrace(*cliConfig, fmt.Sprintf("Using command line argument '%s' as CUE schemas directory", configAndStacksInfo.CueDir)) + atmosConfig.Schemas.Cue.BasePath = configAndStacksInfo.CueDir + u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s' as CUE schemas directory", configAndStacksInfo.CueDir)) } if len(configAndStacksInfo.AtmosManifestJsonSchema) > 0 { - cliConfig.Schemas.Atmos.Manifest = configAndStacksInfo.AtmosManifestJsonSchema - u.LogTrace(*cliConfig, fmt.Sprintf("Using command line argument '%s' as path to Atmos JSON Schema", configAndStacksInfo.AtmosManifestJsonSchema)) + atmosConfig.Schemas.Atmos.Manifest = configAndStacksInfo.AtmosManifestJsonSchema + u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s' as path to Atmos JSON Schema", configAndStacksInfo.AtmosManifestJsonSchema)) } if len(configAndStacksInfo.LogsLevel) > 0 { - cliConfig.Logs.Level = configAndStacksInfo.LogsLevel - u.LogTrace(*cliConfig, fmt.Sprintf("Using command line argument '%s=%s'", LogsLevelFlag, configAndStacksInfo.LogsLevel)) + atmosConfig.Logs.Level = configAndStacksInfo.LogsLevel + u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s=%s'", LogsLevelFlag, configAndStacksInfo.LogsLevel)) } if len(configAndStacksInfo.LogsFile) > 0 { - cliConfig.Logs.File = configAndStacksInfo.LogsFile - u.LogTrace(*cliConfig, fmt.Sprintf("Using command line argument '%s=%s'", LogsFileFlag, configAndStacksInfo.LogsFile)) + atmosConfig.Logs.File = configAndStacksInfo.LogsFile + u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s=%s'", LogsFileFlag, configAndStacksInfo.LogsFile)) } if len(configAndStacksInfo.SettingsListMergeStrategy) > 0 { - cliConfig.Settings.ListMergeStrategy = configAndStacksInfo.SettingsListMergeStrategy - u.LogTrace(*cliConfig, fmt.Sprintf("Using command line argument '%s=%s'", SettingsListMergeStrategyFlag, configAndStacksInfo.SettingsListMergeStrategy)) + atmosConfig.Settings.ListMergeStrategy = configAndStacksInfo.SettingsListMergeStrategy + u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s=%s'", SettingsListMergeStrategyFlag, configAndStacksInfo.SettingsListMergeStrategy)) } return nil } -// processStoreConfig creates a store registry from the provided stores config and assigns it to the cliConfig -func processStoreConfig(cliConfig *schema.CliConfiguration) error { - log.Debug("processStoreConfig", "cliConfig.StoresConfig", fmt.Sprintf("%v", cliConfig.StoresConfig)) +// processStoreConfig creates a store registry from the provided stores config and assigns it to the atmosConfig +func processStoreConfig(atmosConfig *schema.AtmosConfiguration) error { + log.Debug("processStoreConfig", "atmosConfig.StoresConfig", fmt.Sprintf("%v", atmosConfig.StoresConfig)) - storeRegistry, err := store.NewStoreRegistry(&cliConfig.StoresConfig) + storeRegistry, err := store.NewStoreRegistry(&atmosConfig.StoresConfig) if err != nil { return err } - cliConfig.Stores = storeRegistry + atmosConfig.Stores = storeRegistry return nil } @@ -731,7 +731,7 @@ func getConfigFilePatterns(path string, forGlobMatch bool) []string { return patterns } -func SearchConfigFile(configPath string, cliConfig schema.CliConfiguration) (string, error) { +func SearchConfigFile(configPath string, atmosConfig schema.AtmosConfiguration) (string, error) { // If path already has an extension, verify it exists if ext := filepath.Ext(configPath); ext != "" { if _, err := os.Stat(configPath); err == nil { diff --git a/pkg/describe/describe_affected_test.go b/pkg/describe/describe_affected_test.go index 11c5a3afc..c28dc6e5d 100644 --- a/pkg/describe/describe_affected_test.go +++ b/pkg/describe/describe_affected_test.go @@ -15,13 +15,13 @@ import ( func TestDescribeAffectedWithTargetRefClone(t *testing.T) { configAndStacksInfo := schema.ConfigAndStacksInfo{} - cliConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) + atmosConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) assert.Nil(t, err) // We are using `atmos.yaml` from this dir. This `atmos.yaml` has set base_path: "../../examples/tests", // which will be wrong for the remote repo which is cloned into a temp dir. // Set the correct base path for the cloned remote repo - cliConfig.BasePath = "./examples/tests" + atmosConfig.BasePath = "./examples/tests" // Git reference and commit SHA // Refer to https://git-scm.com/book/en/v2/Git-Internals-Git-References for more details @@ -29,7 +29,7 @@ func TestDescribeAffectedWithTargetRefClone(t *testing.T) { sha := "" affected, _, _, _, err := e.ExecuteDescribeAffectedWithTargetRefClone( - cliConfig, + atmosConfig, ref, sha, "", @@ -50,20 +50,20 @@ func TestDescribeAffectedWithTargetRefClone(t *testing.T) { func TestDescribeAffectedWithTargetRepoPath(t *testing.T) { configAndStacksInfo := schema.ConfigAndStacksInfo{} - cliConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) + atmosConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) assert.Nil(t, err) // We are using `atmos.yaml` from this dir. This `atmos.yaml` has set base_path: "../../examples/tests", // which will be wrong for the remote repo which is cloned into a temp dir. // Set the correct base path for the cloned remote repo - cliConfig.BasePath = "./examples/tests" + atmosConfig.BasePath = "./examples/tests" // Point to the same local repository // This will compare this local repository with itself as the remote target, which should result in an empty `affected` list repoPath := "../../" affected, _, _, _, err := e.ExecuteDescribeAffectedWithTargetRepoPath( - cliConfig, + atmosConfig, repoPath, true, true, diff --git a/pkg/describe/describe_dependents_test.go b/pkg/describe/describe_dependents_test.go index 2df553bd4..f910362d0 100644 --- a/pkg/describe/describe_dependents_test.go +++ b/pkg/describe/describe_dependents_test.go @@ -14,13 +14,13 @@ import ( func TestDescribeDependents(t *testing.T) { configAndStacksInfo := schema.ConfigAndStacksInfo{} - cliConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) + atmosConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) assert.Nil(t, err) component := "test/test-component" stack := "tenant1-ue2-test-1" - dependents, err := e.ExecuteDescribeDependents(cliConfig, component, stack, false) + dependents, err := e.ExecuteDescribeDependents(atmosConfig, component, stack, false) assert.Nil(t, err) assert.Equal(t, 1, len(dependents)) @@ -32,13 +32,13 @@ func TestDescribeDependents(t *testing.T) { func TestDescribeDependents2(t *testing.T) { configAndStacksInfo := schema.ConfigAndStacksInfo{} - cliConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) + atmosConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) assert.Nil(t, err) component := "test/test-component" stack := "tenant1-ue2-dev" - dependents, err := e.ExecuteDescribeDependents(cliConfig, component, stack, false) + dependents, err := e.ExecuteDescribeDependents(atmosConfig, component, stack, false) assert.Nil(t, err) assert.Equal(t, 4, len(dependents)) diff --git a/pkg/describe/describe_stacks.go b/pkg/describe/describe_stacks.go index 7cea75cee..00076ae2d 100644 --- a/pkg/describe/describe_stacks.go +++ b/pkg/describe/describe_stacks.go @@ -7,7 +7,7 @@ import ( // ExecuteDescribeStacks processes stack manifests and returns the final map of stacks and components func ExecuteDescribeStacks( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, filterByStack string, components []string, componentTypes []string, @@ -16,5 +16,5 @@ func ExecuteDescribeStacks( includeEmptyStacks bool, ) (map[string]any, error) { - return e.ExecuteDescribeStacks(cliConfig, filterByStack, components, componentTypes, sections, ignoreMissingFiles, true, includeEmptyStacks) + return e.ExecuteDescribeStacks(atmosConfig, filterByStack, components, componentTypes, sections, ignoreMissingFiles, true, includeEmptyStacks) } diff --git a/pkg/describe/describe_stacks_test.go b/pkg/describe/describe_stacks_test.go index eecf17fa9..b6fe06078 100644 --- a/pkg/describe/describe_stacks_test.go +++ b/pkg/describe/describe_stacks_test.go @@ -13,10 +13,10 @@ import ( func TestDescribeStacks(t *testing.T) { configAndStacksInfo := schema.ConfigAndStacksInfo{} - cliConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) + atmosConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) assert.Nil(t, err) - stacks, err := ExecuteDescribeStacks(cliConfig, "", nil, nil, nil, false, false) + stacks, err := ExecuteDescribeStacks(atmosConfig, "", nil, nil, nil, false, false) assert.Nil(t, err) dependentsYaml, err := u.ConvertToYAML(stacks) @@ -27,12 +27,12 @@ func TestDescribeStacks(t *testing.T) { func TestDescribeStacksWithFilter1(t *testing.T) { configAndStacksInfo := schema.ConfigAndStacksInfo{} - cliConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) + atmosConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) assert.Nil(t, err) stack := "tenant1-ue2-dev" - stacks, err := ExecuteDescribeStacks(cliConfig, stack, nil, nil, nil, false, false) + stacks, err := ExecuteDescribeStacks(atmosConfig, stack, nil, nil, nil, false, false) assert.Nil(t, err) dependentsYaml, err := u.ConvertToYAML(stacks) @@ -43,13 +43,13 @@ func TestDescribeStacksWithFilter1(t *testing.T) { func TestDescribeStacksWithFilter2(t *testing.T) { configAndStacksInfo := schema.ConfigAndStacksInfo{} - cliConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) + atmosConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) assert.Nil(t, err) stack := "tenant1-ue2-dev" components := []string{"infra/vpc"} - stacks, err := ExecuteDescribeStacks(cliConfig, stack, components, nil, nil, false, false) + stacks, err := ExecuteDescribeStacks(atmosConfig, stack, components, nil, nil, false, false) assert.Nil(t, err) dependentsYaml, err := u.ConvertToYAML(stacks) @@ -60,13 +60,13 @@ func TestDescribeStacksWithFilter2(t *testing.T) { func TestDescribeStacksWithFilter3(t *testing.T) { configAndStacksInfo := schema.ConfigAndStacksInfo{} - cliConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) + atmosConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) assert.Nil(t, err) stack := "tenant1-ue2-dev" sections := []string{"vars"} - stacks, err := ExecuteDescribeStacks(cliConfig, stack, nil, nil, sections, false, false) + stacks, err := ExecuteDescribeStacks(atmosConfig, stack, nil, nil, sections, false, false) assert.Nil(t, err) dependentsYaml, err := u.ConvertToYAML(stacks) @@ -77,13 +77,13 @@ func TestDescribeStacksWithFilter3(t *testing.T) { func TestDescribeStacksWithFilter4(t *testing.T) { configAndStacksInfo := schema.ConfigAndStacksInfo{} - cliConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) + atmosConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) assert.Nil(t, err) componentTypes := []string{"terraform"} sections := []string{"none"} - stacks, err := ExecuteDescribeStacks(cliConfig, "", nil, componentTypes, sections, false, false) + stacks, err := ExecuteDescribeStacks(atmosConfig, "", nil, componentTypes, sections, false, false) assert.Nil(t, err) dependentsYaml, err := u.ConvertToYAML(stacks) @@ -94,14 +94,14 @@ func TestDescribeStacksWithFilter4(t *testing.T) { func TestDescribeStacksWithFilter5(t *testing.T) { configAndStacksInfo := schema.ConfigAndStacksInfo{} - cliConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) + atmosConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) assert.Nil(t, err) componentTypes := []string{"terraform"} components := []string{"top-level-component1"} sections := []string{"vars"} - stacks, err := ExecuteDescribeStacks(cliConfig, "", components, componentTypes, sections, false, false) + stacks, err := ExecuteDescribeStacks(atmosConfig, "", components, componentTypes, sections, false, false) assert.Nil(t, err) assert.Equal(t, 8, len(stacks)) @@ -125,7 +125,7 @@ func TestDescribeStacksWithFilter5(t *testing.T) { func TestDescribeStacksWithFilter6(t *testing.T) { configAndStacksInfo := schema.ConfigAndStacksInfo{} - cliConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) + atmosConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) assert.Nil(t, err) stack := "tenant1-ue2-dev" @@ -133,7 +133,7 @@ func TestDescribeStacksWithFilter6(t *testing.T) { components := []string{"top-level-component1"} sections := []string{"workspace"} - stacks, err := ExecuteDescribeStacks(cliConfig, "tenant1-ue2-dev", components, componentTypes, sections, false, false) + stacks, err := ExecuteDescribeStacks(atmosConfig, "tenant1-ue2-dev", components, componentTypes, sections, false, false) assert.Nil(t, err) assert.Equal(t, 1, len(stacks)) @@ -152,7 +152,7 @@ func TestDescribeStacksWithFilter6(t *testing.T) { func TestDescribeStacksWithFilter7(t *testing.T) { configAndStacksInfo := schema.ConfigAndStacksInfo{} - cliConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) + atmosConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) assert.Nil(t, err) stack := "tenant1-ue2-dev" @@ -160,7 +160,7 @@ func TestDescribeStacksWithFilter7(t *testing.T) { components := []string{"test/test-component-override-3"} sections := []string{"workspace"} - stacks, err := ExecuteDescribeStacks(cliConfig, stack, components, componentTypes, sections, false, false) + stacks, err := ExecuteDescribeStacks(atmosConfig, stack, components, componentTypes, sections, false, false) assert.Nil(t, err) assert.Equal(t, 1, len(stacks)) @@ -179,15 +179,15 @@ func TestDescribeStacksWithFilter7(t *testing.T) { func TestDescribeStacksWithEmptyStacks(t *testing.T) { configAndStacksInfo := schema.ConfigAndStacksInfo{} - cliConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) + atmosConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) assert.Nil(t, err) - stacks, err := ExecuteDescribeStacks(cliConfig, "", nil, nil, nil, false, false) + stacks, err := ExecuteDescribeStacks(atmosConfig, "", nil, nil, nil, false, false) assert.Nil(t, err) initialStackCount := len(stacks) - stacksWithEmpty, err := ExecuteDescribeStacks(cliConfig, "", nil, nil, nil, false, true) + stacksWithEmpty, err := ExecuteDescribeStacks(atmosConfig, "", nil, nil, nil, false, true) assert.Nil(t, err) assert.Greater(t, len(stacksWithEmpty), initialStackCount, "Should include more stacks when empty stacks are included") @@ -215,14 +215,14 @@ func TestDescribeStacksWithEmptyStacks(t *testing.T) { func TestDescribeStacksWithVariousEmptyStacks(t *testing.T) { configAndStacksInfo := schema.ConfigAndStacksInfo{} - cliConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) + atmosConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) assert.Nil(t, err) - stacksWithoutEmpty, err := ExecuteDescribeStacks(cliConfig, "", nil, nil, nil, false, false) + stacksWithoutEmpty, err := ExecuteDescribeStacks(atmosConfig, "", nil, nil, nil, false, false) assert.Nil(t, err) initialCount := len(stacksWithoutEmpty) - stacksWithEmpty, err := ExecuteDescribeStacks(cliConfig, "", nil, nil, nil, false, true) + stacksWithEmpty, err := ExecuteDescribeStacks(atmosConfig, "", nil, nil, nil, false, true) assert.Nil(t, err) assert.Greater(t, len(stacksWithEmpty), initialCount, "Should have more stacks when including empty ones") diff --git a/pkg/generate/terraform_generate_varfiles_test.go b/pkg/generate/terraform_generate_varfiles_test.go index 615d94eee..eb61b5ce7 100644 --- a/pkg/generate/terraform_generate_varfiles_test.go +++ b/pkg/generate/terraform_generate_varfiles_test.go @@ -15,7 +15,7 @@ import ( ) func TestTerraformGenerateVarfiles(t *testing.T) { - cliConfig, err := cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, true) + atmosConfig, err := cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, true) assert.Nil(t, err) tempDir, err := os.MkdirTemp("", strconv.FormatInt(time.Now().Unix(), 10)) @@ -31,6 +31,6 @@ func TestTerraformGenerateVarfiles(t *testing.T) { filePattern := filepath.Join(tempDir, "varfiles/{tenant}-{environment}-{stage}-{component}.tfvars") format := "hcl" - err = e.ExecuteTerraformGenerateVarfiles(cliConfig, filePattern, format, stacks, components) + err = e.ExecuteTerraformGenerateVarfiles(atmosConfig, filePattern, format, stacks, components) assert.Nil(t, err) } diff --git a/pkg/list/list_components_test.go b/pkg/list/list_components_test.go index 1d30b020f..8cb86ade8 100644 --- a/pkg/list/list_components_test.go +++ b/pkg/list/list_components_test.go @@ -18,10 +18,10 @@ const ( func TestListComponents(t *testing.T) { configAndStacksInfo := schema.ConfigAndStacksInfo{} - cliConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) + atmosConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) assert.Nil(t, err) - stacksMap, err := e.ExecuteDescribeStacks(cliConfig, "", nil, nil, + stacksMap, err := e.ExecuteDescribeStacks(atmosConfig, "", nil, nil, nil, false, false, false) assert.Nil(t, err) @@ -38,10 +38,10 @@ func TestListComponents(t *testing.T) { func TestListComponentsWithStack(t *testing.T) { configAndStacksInfo := schema.ConfigAndStacksInfo{} - cliConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) + atmosConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) assert.Nil(t, err) - stacksMap, err := e.ExecuteDescribeStacks(cliConfig, testStack, nil, nil, + stacksMap, err := e.ExecuteDescribeStacks(atmosConfig, testStack, nil, nil, nil, false, false, false) assert.Nil(t, err) diff --git a/pkg/list/list_stacks_test.go b/pkg/list/list_stacks_test.go index 190b69016..87b17d6a7 100644 --- a/pkg/list/list_stacks_test.go +++ b/pkg/list/list_stacks_test.go @@ -18,10 +18,10 @@ const ( func TestListStacks(t *testing.T) { configAndStacksInfo := schema.ConfigAndStacksInfo{} - cliConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) + atmosConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) assert.Nil(t, err) - stacksMap, err := e.ExecuteDescribeStacks(cliConfig, "", nil, nil, + stacksMap, err := e.ExecuteDescribeStacks(atmosConfig, "", nil, nil, nil, false, false, false) assert.Nil(t, err) @@ -34,11 +34,11 @@ func TestListStacks(t *testing.T) { func TestListStacksWithComponent(t *testing.T) { configAndStacksInfo := schema.ConfigAndStacksInfo{} - cliConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) + atmosConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) assert.Nil(t, err) component := testComponent - stacksMap, err := e.ExecuteDescribeStacks(cliConfig, component, nil, nil, + stacksMap, err := e.ExecuteDescribeStacks(atmosConfig, component, nil, nil, nil, false, false, false) assert.Nil(t, err) diff --git a/pkg/logger/logger.go b/pkg/logger/logger.go index 6735229e2..648641325 100644 --- a/pkg/logger/logger.go +++ b/pkg/logger/logger.go @@ -31,7 +31,7 @@ func NewLogger(logLevel LogLevel, file string) (*Logger, error) { }, nil } -func NewLoggerFromCliConfig(cfg schema.CliConfiguration) (*Logger, error) { +func NewLoggerFromCliConfig(cfg schema.AtmosConfiguration) (*Logger, error) { logLevel, err := ParseLogLevel(cfg.Logs.Level) if err != nil { return nil, err diff --git a/pkg/logger/logger_test.go b/pkg/logger/logger_test.go index cd41767b9..f6dccd5b0 100644 --- a/pkg/logger/logger_test.go +++ b/pkg/logger/logger_test.go @@ -48,14 +48,14 @@ func TestNewLogger(t *testing.T) { } func TestNewLoggerFromCliConfig(t *testing.T) { - cliConfig := schema.CliConfiguration{ + atmosConfig := schema.AtmosConfiguration{ Logs: schema.Logs{ Level: "Info", File: "/dev/stdout", }, } - logger, err := NewLoggerFromCliConfig(cliConfig) + logger, err := NewLoggerFromCliConfig(atmosConfig) assert.NoError(t, err) assert.NotNil(t, logger) assert.Equal(t, LogLevelInfo, logger.LogLevel) diff --git a/pkg/merge/merge.go b/pkg/merge/merge.go index cc4310a1d..937e06cc3 100644 --- a/pkg/merge/merge.go +++ b/pkg/merge/merge.go @@ -77,28 +77,28 @@ func MergeWithOptions( // Merge takes a list of maps as input, deep-merges the items in the order they are defined in the list, and returns a single map with the merged contents func Merge( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, inputs []map[string]any, ) (map[string]any, error) { - if cliConfig.Settings.ListMergeStrategy == "" { - cliConfig.Settings.ListMergeStrategy = ListMergeStrategyReplace + if atmosConfig.Settings.ListMergeStrategy == "" { + atmosConfig.Settings.ListMergeStrategy = ListMergeStrategyReplace } - if cliConfig.Settings.ListMergeStrategy != ListMergeStrategyReplace && - cliConfig.Settings.ListMergeStrategy != ListMergeStrategyAppend && - cliConfig.Settings.ListMergeStrategy != ListMergeStrategyMerge { + if atmosConfig.Settings.ListMergeStrategy != ListMergeStrategyReplace && + atmosConfig.Settings.ListMergeStrategy != ListMergeStrategyAppend && + atmosConfig.Settings.ListMergeStrategy != ListMergeStrategyMerge { return nil, fmt.Errorf("invalid Atmos manifests list merge strategy '%s'.\n"+ "Supported list merge strategies are: %s.", - cliConfig.Settings.ListMergeStrategy, + atmosConfig.Settings.ListMergeStrategy, fmt.Sprintf("%s, %s, %s", ListMergeStrategyReplace, ListMergeStrategyAppend, ListMergeStrategyMerge)) } sliceDeepCopy := false appendSlice := false - if cliConfig.Settings.ListMergeStrategy == ListMergeStrategyMerge { + if atmosConfig.Settings.ListMergeStrategy == ListMergeStrategyMerge { sliceDeepCopy = true - } else if cliConfig.Settings.ListMergeStrategy == ListMergeStrategyAppend { + } else if atmosConfig.Settings.ListMergeStrategy == ListMergeStrategyAppend { appendSlice = true } diff --git a/pkg/merge/merge_test.go b/pkg/merge/merge_test.go index 0a0d84e3f..5b5e809c8 100644 --- a/pkg/merge/merge_test.go +++ b/pkg/merge/merge_test.go @@ -10,7 +10,7 @@ import ( ) func TestMergeBasic(t *testing.T) { - cliConfig := schema.CliConfiguration{} + atmosConfig := schema.AtmosConfiguration{} map1 := map[string]any{"foo": "bar"} map2 := map[string]any{"baz": "bat"} @@ -18,13 +18,13 @@ func TestMergeBasic(t *testing.T) { inputs := []map[string]any{map1, map2} expected := map[string]any{"foo": "bar", "baz": "bat"} - result, err := Merge(cliConfig, inputs) + result, err := Merge(atmosConfig, inputs) assert.Nil(t, err) assert.Equal(t, expected, result) } func TestMergeBasicOverride(t *testing.T) { - cliConfig := schema.CliConfiguration{} + atmosConfig := schema.AtmosConfiguration{} map1 := map[string]any{"foo": "bar"} map2 := map[string]any{"baz": "bat"} @@ -33,14 +33,14 @@ func TestMergeBasicOverride(t *testing.T) { inputs := []map[string]any{map1, map2, map3} expected := map[string]any{"foo": "ood", "baz": "bat"} - result, err := Merge(cliConfig, inputs) + result, err := Merge(atmosConfig, inputs) assert.Nil(t, err) assert.Equal(t, expected, result) } func TestMergeListReplace(t *testing.T) { - cliConfig := schema.CliConfiguration{ - Settings: schema.CliSettings{ + atmosConfig := schema.AtmosConfiguration{ + Settings: schema.AtmosSettings{ ListMergeStrategy: ListMergeStrategyReplace, }, } @@ -56,7 +56,7 @@ func TestMergeListReplace(t *testing.T) { inputs := []map[string]any{map1, map2} expected := map[string]any{"list": []any{"4", "5", "6"}} - result, err := Merge(cliConfig, inputs) + result, err := Merge(atmosConfig, inputs) assert.Nil(t, err) assert.Equal(t, expected, result) @@ -66,8 +66,8 @@ func TestMergeListReplace(t *testing.T) { } func TestMergeListAppend(t *testing.T) { - cliConfig := schema.CliConfiguration{ - Settings: schema.CliSettings{ + atmosConfig := schema.AtmosConfiguration{ + Settings: schema.AtmosSettings{ ListMergeStrategy: ListMergeStrategyAppend, }, } @@ -83,7 +83,7 @@ func TestMergeListAppend(t *testing.T) { inputs := []map[string]any{map1, map2} expected := map[string]any{"list": []any{"1", "2", "3", "4", "5", "6"}} - result, err := Merge(cliConfig, inputs) + result, err := Merge(atmosConfig, inputs) assert.Nil(t, err) assert.Equal(t, expected, result) @@ -93,8 +93,8 @@ func TestMergeListAppend(t *testing.T) { } func TestMergeListMerge(t *testing.T) { - cliConfig := schema.CliConfiguration{ - Settings: schema.CliSettings{ + atmosConfig := schema.AtmosConfiguration{ + Settings: schema.AtmosSettings{ ListMergeStrategy: ListMergeStrategyMerge, }, } @@ -123,7 +123,7 @@ func TestMergeListMerge(t *testing.T) { inputs := []map[string]any{map1, map2} - result, err := Merge(cliConfig, inputs) + result, err := Merge(atmosConfig, inputs) assert.Nil(t, err) var mergedList []any diff --git a/pkg/schema/schema.go b/pkg/schema/schema.go index 52c09de91..8108be1bd 100644 --- a/pkg/schema/schema.go +++ b/pkg/schema/schema.go @@ -4,8 +4,8 @@ import "github.com/cloudposse/atmos/pkg/store" type AtmosSectionMapType = map[string]any -// CliConfiguration structure represents schema for `atmos.yaml` CLI config -type CliConfiguration struct { +// AtmosConfiguration structure represents schema for `atmos.yaml` CLI config +type AtmosConfiguration struct { BasePath string `yaml:"base_path" json:"base_path" mapstructure:"base_path"` Components Components `yaml:"components" json:"components" mapstructure:"components"` Stacks Stacks `yaml:"stacks" json:"stacks" mapstructure:"stacks"` @@ -16,7 +16,7 @@ type CliConfiguration struct { Integrations Integrations `yaml:"integrations,omitempty" json:"integrations,omitempty" mapstructure:"integrations"` Schemas Schemas `yaml:"schemas,omitempty" json:"schemas,omitempty" mapstructure:"schemas"` Templates Templates `yaml:"templates,omitempty" json:"templates,omitempty" mapstructure:"templates"` - Settings CliSettings `yaml:"settings,omitempty" json:"settings,omitempty" mapstructure:"settings"` + Settings AtmosSettings `yaml:"settings,omitempty" json:"settings,omitempty" mapstructure:"settings"` StoresConfig store.StoresConfig `yaml:"stores,omitempty" json:"stores,omitempty" mapstructure:"stores"` Vendor Vendor `yaml:"vendor,omitempty" json:"vendor,omitempty" mapstructure:"vendor"` Initialized bool `yaml:"initialized" json:"initialized" mapstructure:"initialized"` @@ -37,7 +37,7 @@ type CliConfiguration struct { Stores store.StoreRegistry `yaml:"stores_registry,omitempty" json:"stores_registry,omitempty" mapstructure:"stores_registry"` } -type CliSettings struct { +type AtmosSettings struct { ListMergeStrategy string `yaml:"list_merge_strategy" json:"list_merge_strategy" mapstructure:"list_merge_strategy"` Docs Docs `yaml:"docs,omitempty" json:"docs,omitempty" mapstructure:"docs"` } diff --git a/pkg/spacelift/spacelift_stack_processor.go b/pkg/spacelift/spacelift_stack_processor.go index 353b0166b..116672689 100644 --- a/pkg/spacelift/spacelift_stack_processor.go +++ b/pkg/spacelift/spacelift_stack_processor.go @@ -28,15 +28,15 @@ func CreateSpaceliftStacks( stackConfigPathTemplate string, ) (map[string]any, error) { - cliConfig, err := cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, true) + atmosConfig, err := cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, true) if err != nil { - u.LogError(cliConfig, err) + u.LogError(atmosConfig, err) return nil, err } if len(filePaths) > 0 { _, stacks, rawStackConfigs, err := s.ProcessYAMLConfigFiles( - cliConfig, + atmosConfig, stacksBasePath, terraformComponentsBasePath, helmfileComponentsBasePath, @@ -46,12 +46,12 @@ func CreateSpaceliftStacks( false, ) if err != nil { - u.LogError(cliConfig, err) + u.LogError(atmosConfig, err) return nil, err } return TransformStackConfigToSpaceliftStacks( - cliConfig, + atmosConfig, stacks, stackConfigPathTemplate, "", @@ -60,25 +60,25 @@ func CreateSpaceliftStacks( ) } else { _, stacks, rawStackConfigs, err := s.ProcessYAMLConfigFiles( - cliConfig, - cliConfig.StacksBaseAbsolutePath, - cliConfig.TerraformDirAbsolutePath, - cliConfig.HelmfileDirAbsolutePath, - cliConfig.StackConfigFilesAbsolutePaths, + atmosConfig, + atmosConfig.StacksBaseAbsolutePath, + atmosConfig.TerraformDirAbsolutePath, + atmosConfig.HelmfileDirAbsolutePath, + atmosConfig.StackConfigFilesAbsolutePaths, processStackDeps, processComponentDeps, false, ) if err != nil { - u.LogError(cliConfig, err) + u.LogError(atmosConfig, err) return nil, err } return TransformStackConfigToSpaceliftStacks( - cliConfig, + atmosConfig, stacks, stackConfigPathTemplate, - e.GetStackNamePattern(cliConfig), + e.GetStackNamePattern(atmosConfig), processImports, rawStackConfigs, ) @@ -87,7 +87,7 @@ func CreateSpaceliftStacks( // TransformStackConfigToSpaceliftStacks takes a map of stack manifests and transforms it to a map of Spacelift stacks func TransformStackConfigToSpaceliftStacks( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, stacks map[string]any, stackConfigPathTemplate string, stackNamePattern string, @@ -187,7 +187,7 @@ func TransformStackConfigToSpaceliftStacks( if stackNamePattern != "" { contextPrefix, err = cfg.GetContextPrefix(stackName, context, stackNamePattern, stackName) if err != nil { - u.LogError(cliConfig, err) + u.LogError(atmosConfig, err) return nil, err } } else { @@ -255,9 +255,9 @@ func TransformStackConfigToSpaceliftStacks( spaceliftConfig["deps_all"] = componentDepsAll // Terraform workspace - workspace, err := e.BuildTerraformWorkspace(cliConfig, configAndStacksInfo) + workspace, err := e.BuildTerraformWorkspace(atmosConfig, configAndStacksInfo) if err != nil { - u.LogError(cliConfig, err) + u.LogError(atmosConfig, err) return nil, err } spaceliftConfig["workspace"] = workspace @@ -300,7 +300,7 @@ func TransformStackConfigToSpaceliftStacks( component, ) if err != nil { - u.LogError(cliConfig, err) + u.LogError(atmosConfig, err) return nil, err } spaceliftStackNameDependsOnLabels1 = append(spaceliftStackNameDependsOnLabels1, fmt.Sprintf("depends-on:%s", spaceliftStackNameDependsOn)) @@ -360,7 +360,7 @@ func TransformStackConfigToSpaceliftStacks( allStackNames, ) if err != nil { - u.LogError(cliConfig, err) + u.LogError(atmosConfig, err) return nil, err } spaceliftStackNameDependsOnLabels2 = append(spaceliftStackNameDependsOnLabels2, fmt.Sprintf("depends-on:%s", spaceliftStackNameDependsOn)) @@ -378,7 +378,7 @@ func TransformStackConfigToSpaceliftStacks( // Spacelift stack name spaceliftStackName, spaceliftStackNamePattern, err := e.BuildSpaceliftStackName(spaceliftSettings, context, contextPrefix) if err != nil { - u.LogError(cliConfig, err) + u.LogError(atmosConfig, err) return nil, err } @@ -397,7 +397,7 @@ func TransformStackConfigToSpaceliftStacks( spaceliftStackNamePattern, ) er := errors.New(errorMessage) - u.LogError(cliConfig, er) + u.LogError(atmosConfig, er) return nil, er } } diff --git a/pkg/stack/stack_processor.go b/pkg/stack/stack_processor.go index 57ff164f3..fb836beb7 100644 --- a/pkg/stack/stack_processor.go +++ b/pkg/stack/stack_processor.go @@ -8,7 +8,7 @@ import ( // ProcessYAMLConfigFiles takes a list of paths to stack manifests, processes and deep-merges all imports, // and returns a list of stack configs func ProcessYAMLConfigFiles( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, stacksBasePath string, terraformComponentsBasePath string, helmfileComponentsBasePath string, @@ -23,7 +23,7 @@ func ProcessYAMLConfigFiles( error, ) { return exec.ProcessYAMLConfigFiles( - cliConfig, + atmosConfig, stacksBasePath, terraformComponentsBasePath, helmfileComponentsBasePath, @@ -35,7 +35,7 @@ func ProcessYAMLConfigFiles( } func ProcessYAMLConfigFile( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, basePath string, filePath string, importsConfig map[string]map[string]any, @@ -56,7 +56,7 @@ func ProcessYAMLConfigFile( error, ) { return exec.ProcessYAMLConfigFile( - cliConfig, + atmosConfig, basePath, filePath, importsConfig, @@ -74,7 +74,7 @@ func ProcessYAMLConfigFile( // ProcessStackConfig takes a stack manifest, deep-merges all variables, settings, environments and backends, // and returns the final stack configuration for all Terraform and helmfile components func ProcessStackConfig( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, stacksBasePath string, terraformComponentsBasePath string, helmfileComponentsBasePath string, @@ -88,7 +88,7 @@ func ProcessStackConfig( checkBaseComponentExists bool, ) (map[string]any, error) { return exec.ProcessStackConfig( - cliConfig, + atmosConfig, stacksBasePath, terraformComponentsBasePath, helmfileComponentsBasePath, diff --git a/pkg/stack/stack_processor_test.go b/pkg/stack/stack_processor_test.go index 0505163a5..e7c39d26d 100644 --- a/pkg/stack/stack_processor_test.go +++ b/pkg/stack/stack_processor_test.go @@ -24,7 +24,7 @@ func TestStackProcessor(t *testing.T) { processStackDeps := true processComponentDeps := true - cliConfig := schema.CliConfiguration{ + atmosConfig := schema.AtmosConfiguration{ Templates: schema.Templates{ Settings: schema.TemplatesSettings{ Enabled: true, @@ -39,7 +39,7 @@ func TestStackProcessor(t *testing.T) { } var listResult, mapResult, _, err = ProcessYAMLConfigFiles( - cliConfig, + atmosConfig, stacksBasePath, terraformComponentsBasePath, helmfileComponentsBasePath, diff --git a/pkg/utils/hcl_utils.go b/pkg/utils/hcl_utils.go index a40bf6659..601346fed 100644 --- a/pkg/utils/hcl_utils.go +++ b/pkg/utils/hcl_utils.go @@ -30,7 +30,7 @@ func PrintAsHcl(data any) error { // WriteToFileAsHcl converts the provided value to HCL (HashiCorp Language) and writes it to the specified file func WriteToFileAsHcl( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, filePath string, data any, fileMode os.FileMode, @@ -48,7 +48,7 @@ func WriteToFileAsHcl( defer func(f *os.File) { err := f.Close() if err != nil { - LogWarning(cliConfig, err.Error()) + LogWarning(atmosConfig, err.Error()) } }(f) @@ -89,7 +89,7 @@ func ConvertToHclAst(data any) (ast.Node, error) { // https://dev.to/pdcommunity/write-terraform-files-in-go-with-hclwrite-2e1j // https://pkg.go.dev/github.com/hashicorp/hcl/v2/hclwrite func WriteTerraformBackendConfigToFileAsHcl( - cliConfig schema.CliConfiguration, + atmosConfig schema.AtmosConfiguration, filePath string, backendType string, backendConfig map[string]any, @@ -129,7 +129,7 @@ func WriteTerraformBackendConfigToFileAsHcl( defer func(f *os.File) { err := f.Close() if err != nil { - LogWarning(cliConfig, err.Error()) + LogWarning(atmosConfig, err.Error()) } }(f) diff --git a/pkg/utils/json_utils.go b/pkg/utils/json_utils.go index d9e9c53fc..9107415a6 100644 --- a/pkg/utils/json_utils.go +++ b/pkg/utils/json_utils.go @@ -29,12 +29,12 @@ func PrintAsJSON(data any) error { } // PrintAsJSONToFileDescriptor prints the provided value as JSON document to a file descriptor -func PrintAsJSONToFileDescriptor(cliConfig schema.CliConfiguration, data any) error { +func PrintAsJSONToFileDescriptor(atmosConfig schema.AtmosConfiguration, data any) error { j, err := ConvertToJSON(data) if err != nil { return err } - LogInfo(cliConfig, j) + LogInfo(atmosConfig, j) return nil } diff --git a/pkg/utils/log_utils.go b/pkg/utils/log_utils.go index e26edd7b8..fd6463691 100644 --- a/pkg/utils/log_utils.go +++ b/pkg/utils/log_utils.go @@ -30,9 +30,9 @@ func PrintMessageInColor(message string, messageColor *color.Color) { } // LogErrorAndExit logs errors to std.Error and exits with an error code -func LogErrorAndExit(cliConfig schema.CliConfiguration, err error) { +func LogErrorAndExit(atmosConfig schema.AtmosConfiguration, err error) { if err != nil { - LogError(cliConfig, err) + LogError(atmosConfig, err) // Find the executed command's exit code from the error var exitError *exec.ExitError @@ -46,7 +46,7 @@ func LogErrorAndExit(cliConfig schema.CliConfiguration, err error) { } // LogError logs errors to std.Error -func LogError(cliConfig schema.CliConfiguration, err error) { +func LogError(atmosConfig schema.AtmosConfiguration, err error) { if err != nil { c := color.New(color.FgRed) _, printErr := c.Fprintln(color.Error, err.Error()+"\n") @@ -58,65 +58,65 @@ func LogError(cliConfig schema.CliConfiguration, err error) { } // Print stack trace - if cliConfig.Logs.Level == LogLevelTrace { + if atmosConfig.Logs.Level == LogLevelTrace { debug.PrintStack() } } } // LogTrace logs the provided trace message -func LogTrace(cliConfig schema.CliConfiguration, message string) { - if cliConfig.Logs.Level == LogLevelTrace { - log(cliConfig, color.New(color.FgCyan), message) +func LogTrace(atmosConfig schema.AtmosConfiguration, message string) { + if atmosConfig.Logs.Level == LogLevelTrace { + log(atmosConfig, color.New(color.FgCyan), message) } } // LogDebug logs the provided debug message -func LogDebug(cliConfig schema.CliConfiguration, message string) { - if cliConfig.Logs.Level == LogLevelTrace || - cliConfig.Logs.Level == LogLevelDebug { +func LogDebug(atmosConfig schema.AtmosConfiguration, message string) { + if atmosConfig.Logs.Level == LogLevelTrace || + atmosConfig.Logs.Level == LogLevelDebug { - log(cliConfig, color.New(color.FgCyan), message) + log(atmosConfig, color.New(color.FgCyan), message) } } // LogInfo logs the provided info message -func LogInfo(cliConfig schema.CliConfiguration, message string) { +func LogInfo(atmosConfig schema.AtmosConfiguration, message string) { // Info level is default, it's used if not set in `atmos.yaml` in the `logs.level` section - if cliConfig.Logs.Level == "" || - cliConfig.Logs.Level == LogLevelTrace || - cliConfig.Logs.Level == LogLevelDebug || - cliConfig.Logs.Level == LogLevelInfo { + if atmosConfig.Logs.Level == "" || + atmosConfig.Logs.Level == LogLevelTrace || + atmosConfig.Logs.Level == LogLevelDebug || + atmosConfig.Logs.Level == LogLevelInfo { - log(cliConfig, color.New(color.Reset), message) + log(atmosConfig, color.New(color.Reset), message) } } // LogWarning logs the provided warning message -func LogWarning(cliConfig schema.CliConfiguration, message string) { - if cliConfig.Logs.Level == LogLevelTrace || - cliConfig.Logs.Level == LogLevelDebug || - cliConfig.Logs.Level == LogLevelInfo || - cliConfig.Logs.Level == LogLevelWarning { +func LogWarning(atmosConfig schema.AtmosConfiguration, message string) { + if atmosConfig.Logs.Level == LogLevelTrace || + atmosConfig.Logs.Level == LogLevelDebug || + atmosConfig.Logs.Level == LogLevelInfo || + atmosConfig.Logs.Level == LogLevelWarning { - log(cliConfig, color.New(color.FgYellow), message) + log(atmosConfig, color.New(color.FgYellow), message) } } -func log(cliConfig schema.CliConfiguration, logColor *color.Color, message string) { - if cliConfig.Logs.File != "" { - if cliConfig.Logs.File == "/dev/stdout" { +func log(atmosConfig schema.AtmosConfiguration, logColor *color.Color, message string) { + if atmosConfig.Logs.File != "" { + if atmosConfig.Logs.File == "/dev/stdout" { _, err := logColor.Fprintln(os.Stdout, message) if err != nil { color.Red("%s\n", err) } - } else if cliConfig.Logs.File == "/dev/stderr" { + } else if atmosConfig.Logs.File == "/dev/stderr" { _, err := logColor.Fprintln(os.Stderr, message) if err != nil { color.Red("%s\n", err) } } else { - f, err := os.OpenFile(cliConfig.Logs.File, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644) + f, err := os.OpenFile(atmosConfig.Logs.File, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644) if err != nil { color.Red("%s\n", err) return diff --git a/pkg/utils/yaml_utils.go b/pkg/utils/yaml_utils.go index a45c75f4d..e27c6401c 100644 --- a/pkg/utils/yaml_utils.go +++ b/pkg/utils/yaml_utils.go @@ -36,12 +36,12 @@ func PrintAsYAML(data any) error { } // PrintAsYAMLToFileDescriptor prints the provided value as YAML document to a file descriptor -func PrintAsYAMLToFileDescriptor(cliConfig schema.CliConfiguration, data any) error { +func PrintAsYAMLToFileDescriptor(atmosConfig schema.AtmosConfiguration, data any) error { y, err := ConvertToYAML(data) if err != nil { return err } - LogInfo(cliConfig, y) + LogInfo(atmosConfig, y) return nil } diff --git a/pkg/validate/validate_component_test.go b/pkg/validate/validate_component_test.go index 66c0d66e5..63c4ce906 100644 --- a/pkg/validate/validate_component_test.go +++ b/pkg/validate/validate_component_test.go @@ -14,11 +14,11 @@ import ( func TestValidateComponent(t *testing.T) { info := schema.ConfigAndStacksInfo{} - cliConfig, err := cfg.InitCliConfig(info, true) + atmosConfig, err := cfg.InitCliConfig(info, true) assert.Nil(t, err) _, err = e.ExecuteValidateComponent( - cliConfig, + atmosConfig, info, "infra/vpc", "tenant1-ue2-dev", @@ -26,18 +26,18 @@ func TestValidateComponent(t *testing.T) { "opa", []string{"catalog"}, 0) - u.LogError(cliConfig, err) + u.LogError(atmosConfig, err) assert.Error(t, err) } func TestValidateComponent2(t *testing.T) { info := schema.ConfigAndStacksInfo{} - cliConfig, err := cfg.InitCliConfig(info, true) + atmosConfig, err := cfg.InitCliConfig(info, true) assert.Nil(t, err) _, err = e.ExecuteValidateComponent( - cliConfig, + atmosConfig, info, "infra/vpc", "tenant1-ue2-prod", @@ -45,18 +45,18 @@ func TestValidateComponent2(t *testing.T) { "", []string{"catalog/constants"}, 0) - u.LogError(cliConfig, err) + u.LogError(atmosConfig, err) assert.Error(t, err) } func TestValidateComponent3(t *testing.T) { info := schema.ConfigAndStacksInfo{} - cliConfig, err := cfg.InitCliConfig(info, true) + atmosConfig, err := cfg.InitCliConfig(info, true) assert.Nil(t, err) _, err = e.ExecuteValidateComponent( - cliConfig, + atmosConfig, info, "infra/vpc", "tenant1-ue2-staging", @@ -64,18 +64,18 @@ func TestValidateComponent3(t *testing.T) { "", nil, 0) - u.LogError(cliConfig, err) + u.LogError(atmosConfig, err) assert.Error(t, err) } func TestValidateComponent4(t *testing.T) { info := schema.ConfigAndStacksInfo{} - cliConfig, err := cfg.InitCliConfig(info, true) + atmosConfig, err := cfg.InitCliConfig(info, true) assert.Nil(t, err) _, err = e.ExecuteValidateComponent( - cliConfig, + atmosConfig, info, "derived-component-3", "tenant1-ue2-test-1", @@ -83,7 +83,7 @@ func TestValidateComponent4(t *testing.T) { "", nil, 0) - u.LogError(cliConfig, err) + u.LogError(atmosConfig, err) assert.Error(t, err) assert.Equal(t, "'service_1_name' variable length must be greater than 10 chars", err.Error()) } diff --git a/pkg/validate/validate_stacks_test.go b/pkg/validate/validate_stacks_test.go index 9a1bfddad..980d46b09 100644 --- a/pkg/validate/validate_stacks_test.go +++ b/pkg/validate/validate_stacks_test.go @@ -13,12 +13,12 @@ import ( func TestValidateStacksCommand(t *testing.T) { err := e.ExecuteValidateStacksCmd(cmd.ValidateStacksCmd, nil) - u.LogError(schema.CliConfiguration{}, err) + u.LogError(schema.AtmosConfiguration{}, err) assert.NotNil(t, err) } func TestValidateStacksCommandWithAtmosManifestJsonSchema(t *testing.T) { err := e.ExecuteValidateStacksCmd(cmd.ValidateStacksCmd, []string{"--schemas-atmos-manifest", "../quick-start-advanced/stacks/schemas/atmos/atmos-manifest/1.0/atmos-manifest.json"}) - u.LogError(schema.CliConfiguration{}, err) + u.LogError(schema.AtmosConfiguration{}, err) assert.NotNil(t, err) } diff --git a/pkg/vender/component_vendor_test.go b/pkg/vender/component_vendor_test.go index 15311f742..59a61b6a1 100644 --- a/pkg/vender/component_vendor_test.go +++ b/pkg/vender/component_vendor_test.go @@ -13,19 +13,19 @@ import ( ) func TestVendorComponentPullCommand(t *testing.T) { - cliConfig, err := cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, true) + atmosConfig, err := cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, true) assert.Nil(t, err) - cliConfig.Logs.Level = "Trace" + atmosConfig.Logs.Level = "Trace" componentType := "terraform" // Test 'infra/vpc-flow-logs-bucket' component component := "infra/vpc-flow-logs-bucket" - componentConfig, componentPath, err := e.ReadAndProcessComponentVendorConfigFile(cliConfig, component, componentType) + componentConfig, componentPath, err := e.ReadAndProcessComponentVendorConfigFile(atmosConfig, component, componentType) assert.Nil(t, err) - err = e.ExecuteComponentVendorInternal(cliConfig, componentConfig.Spec, component, componentPath, false) + err = e.ExecuteComponentVendorInternal(atmosConfig, componentConfig.Spec, component, componentPath, false) assert.Nil(t, err) // Check if the correct files were pulled and written to the correct folder @@ -38,10 +38,10 @@ func TestVendorComponentPullCommand(t *testing.T) { // Test 'infra/account-map' component component = "infra/account-map" - componentConfig, componentPath, err = e.ReadAndProcessComponentVendorConfigFile(cliConfig, component, componentType) + componentConfig, componentPath, err = e.ReadAndProcessComponentVendorConfigFile(atmosConfig, component, componentType) assert.Nil(t, err) - err = e.ExecuteComponentVendorInternal(cliConfig, componentConfig.Spec, component, componentPath, false) + err = e.ExecuteComponentVendorInternal(atmosConfig, componentConfig.Spec, component, componentPath, false) assert.Nil(t, err) // Check if the correct files were pulled and written to the correct folder diff --git a/pkg/vender/vendor_config_test.go b/pkg/vender/vendor_config_test.go index 4ac21834c..f310221be 100644 --- a/pkg/vender/vendor_config_test.go +++ b/pkg/vender/vendor_config_test.go @@ -17,7 +17,7 @@ func TestVendorConfigScenarios(t *testing.T) { testDir := t.TempDir() // Initialize CLI config with required paths - cliConfig := schema.CliConfiguration{ + atmosConfig := schema.AtmosConfiguration{ BasePath: testDir, Components: schema.Components{ Terraform: schema.Terraform{ @@ -25,7 +25,7 @@ func TestVendorConfigScenarios(t *testing.T) { }, }, } - cliConfig.Logs.Level = "Trace" + atmosConfig.Logs.Level = "Trace" // Setup test component directory componentPath := filepath.Join(testDir, "components", "terraform", "myapp") @@ -52,7 +52,7 @@ spec: assert.Nil(t, err) // Test vendoring with component flag - vendorConfig, exists, configFile, err := e.ReadAndProcessVendorConfigFile(cliConfig, vendorYamlPath, true) + vendorConfig, exists, configFile, err := e.ReadAndProcessVendorConfigFile(atmosConfig, vendorYamlPath, true) assert.Nil(t, err) assert.True(t, exists) assert.NotEmpty(t, configFile) @@ -89,7 +89,7 @@ spec: assert.Nil(t, err) // Test component vendoring - componentConfig, compPath, err := e.ReadAndProcessComponentVendorConfigFile(cliConfig, "myapp", "terraform") + componentConfig, compPath, err := e.ReadAndProcessComponentVendorConfigFile(atmosConfig, "myapp", "terraform") assert.Nil(t, err) assert.NotNil(t, componentConfig) assert.Equal(t, componentPath, compPath) @@ -103,12 +103,12 @@ spec: t.Run("no vendor.yaml or component.yaml", func(t *testing.T) { // Test vendoring with component flag vendorYamlPath := filepath.Join(testDir, "vendor.yaml") - _, exists, _, err := e.ReadAndProcessVendorConfigFile(cliConfig, vendorYamlPath, true) + _, exists, _, err := e.ReadAndProcessVendorConfigFile(atmosConfig, vendorYamlPath, true) assert.Nil(t, err) assert.False(t, exists) // Test component vendoring - _, _, err = e.ReadAndProcessComponentVendorConfigFile(cliConfig, "myapp", "terraform") + _, _, err = e.ReadAndProcessComponentVendorConfigFile(atmosConfig, "myapp", "terraform") assert.Error(t, err) assert.Contains(t, err.Error(), "does not exist") }) @@ -131,7 +131,7 @@ spec: assert.Nil(t, err) // Test vendoring without component flag - vendorConfig, exists, configFile, err := e.ReadAndProcessVendorConfigFile(cliConfig, vendorYamlPath, true) + vendorConfig, exists, configFile, err := e.ReadAndProcessVendorConfigFile(atmosConfig, vendorYamlPath, true) assert.Nil(t, err) assert.True(t, exists) assert.NotEmpty(t, configFile) diff --git a/pkg/workflow/workflow_test.go b/pkg/workflow/workflow_test.go index cdaf7b849..1c38ea75e 100644 --- a/pkg/workflow/workflow_test.go +++ b/pkg/workflow/workflow_test.go @@ -12,10 +12,10 @@ import ( ) func TestWorkflowCommand(t *testing.T) { - cliConfig, err := cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, true) + atmosConfig, err := cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, true) assert.Nil(t, err) - cliConfig.Logs.Level = u.LogLevelTrace + atmosConfig.Logs.Level = u.LogLevelTrace workflow := "test-1" workflowPath := "stacks/workflows/workflow1.yaml" @@ -47,7 +47,7 @@ func TestWorkflowCommand(t *testing.T) { } err = e.ExecuteWorkflow( - cliConfig, + atmosConfig, workflow, workflowPath, &workflowDefinition, @@ -60,7 +60,7 @@ func TestWorkflowCommand(t *testing.T) { assert.Nil(t, err) err = e.ExecuteWorkflow( - cliConfig, + atmosConfig, workflow, workflowPath, &workflowDefinition,