diff --git a/cmd/atlantis_generate_repo_config.go b/cmd/atlantis_generate_repo_config.go index 47e29a64b..9900b1766 100644 --- a/cmd/atlantis_generate_repo_config.go +++ b/cmd/atlantis_generate_repo_config.go @@ -1,7 +1,6 @@ package cmd import ( - "github.com/cloudposse/atmos/pkg/schema" "github.com/spf13/cobra" e "github.com/cloudposse/atmos/internal/exec" @@ -23,7 +22,7 @@ var atlantisGenerateRepoConfigCmd = &cobra.Command{ checkAtmosConfig() err := e.ExecuteAtlantisGenerateRepoConfigCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } }, } diff --git a/cmd/aws_eks_update_kubeconfig.go b/cmd/aws_eks_update_kubeconfig.go index b421a0b21..37452d92e 100644 --- a/cmd/aws_eks_update_kubeconfig.go +++ b/cmd/aws_eks_update_kubeconfig.go @@ -4,7 +4,6 @@ import ( "github.com/spf13/cobra" e "github.com/cloudposse/atmos/internal/exec" - "github.com/cloudposse/atmos/pkg/schema" u "github.com/cloudposse/atmos/pkg/utils" ) @@ -36,7 +35,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.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } }, } diff --git a/cmd/cmd_utils.go b/cmd/cmd_utils.go index 79d3f242a..7ebb3bf02 100644 --- a/cmd/cmd_utils.go +++ b/cmd/cmd_utils.go @@ -62,7 +62,7 @@ func processCustomCommands( if _, exist := existingTopLevelCommands[commandConfig.Name]; exist && topLevel { command = existingTopLevelCommands[commandConfig.Name] } else { - var customCommand = &cobra.Command{ + customCommand := &cobra.Command{ Use: commandConfig.Name, Short: commandConfig.Description, Long: commandConfig.Description, @@ -132,7 +132,7 @@ func processCommandAliases( aliasCmd := strings.TrimSpace(v) aliasFor := fmt.Sprintf("alias for '%s'", aliasCmd) - var aliasCommand = &cobra.Command{ + aliasCommand := &cobra.Command{ Use: alias, Short: aliasFor, Long: aliasFor, @@ -140,13 +140,13 @@ func processCommandAliases( Run: func(cmd *cobra.Command, args []string) { err := cmd.ParseFlags(args) if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } commandToRun := fmt.Sprintf("%s %s %s", os.Args[0], aliasCmd, strings.Join(args, " ")) err = e.ExecuteShell(atmosConfig, commandToRun, commandToRun, ".", nil, false) if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } }, } @@ -170,7 +170,7 @@ func preCustomCommand( ) { var sb strings.Builder - //checking for zero arguments in config + // checking for zero arguments in config if len(commandConfig.Arguments) == 0 { if len(commandConfig.Steps) > 0 { // do nothing here; let the code proceed @@ -182,18 +182,18 @@ func preCustomCommand( fmt.Sprintf("%d. %s %s %s\n", i+1, parentCommand.Use, commandConfig.Name, c.Name), ) } - u.LogInfo(schema.AtmosConfiguration{}, sb.String()) + u.LogInfo(sb.String()) os.Exit(1) } else { // truly invalid, nothing to do - u.LogError(schema.AtmosConfiguration{}, errors.New( + u.LogError(errors.New( "invalid command: no args, no steps, no sub-commands", )) os.Exit(1) } } - //Check on many arguments required and have no default value + // Check on many arguments required and have no default value requiredNoDefaultCount := 0 for _, arg := range commandConfig.Arguments { if arg.Required && arg.Default == "" { @@ -218,7 +218,7 @@ func preCustomCommand( if len(args) > 0 { sb.WriteString(fmt.Sprintf("\nReceived %d argument(s): %s\n", len(args), strings.Join(args, ", "))) } - u.LogErrorAndExit(schema.AtmosConfiguration{}, errors.New(sb.String())) + u.LogErrorAndExit(errors.New(sb.String())) } // Merge user-supplied arguments with defaults @@ -233,7 +233,7 @@ func preCustomCommand( } else { // This theoretically shouldn't happen: sb.WriteString(fmt.Sprintf("Missing required argument '%s' with no default!\n", arg.Name)) - u.LogErrorAndExit(schema.AtmosConfiguration{}, errors.New(sb.String())) + u.LogErrorAndExit(errors.New(sb.String())) } } } @@ -297,20 +297,20 @@ func executeCustomCommand( if fl.Type == "" || fl.Type == "string" { providedFlag, err := flags.GetString(fl.Name) if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } flagsData[fl.Name] = providedFlag } else if fl.Type == "bool" { boolFlag, err := flags.GetBool(fl.Name) if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } flagsData[fl.Name] = boolFlag } } // Prepare template data - var data = map[string]any{ + data := map[string]any{ "Arguments": argumentsData, "Flags": flagsData, } @@ -321,27 +321,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(atmosConfig, err) + u.LogErrorAndExit(err) } if component == "" || component == "" { - u.LogErrorAndExit(atmosConfig, fmt.Errorf("the command defines an invalid 'component_config.component: %s' in '%s'", + u.LogErrorAndExit(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(atmosConfig, err) + u.LogErrorAndExit(err) } if stack == "" || stack == "" { - u.LogErrorAndExit(atmosConfig, fmt.Errorf("the command defines an invalid 'component_config.stack: %s' in '%s'", + u.LogErrorAndExit(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(atmosConfig, err) + u.LogErrorAndExit(err) } data["ComponentConfig"] = componentConfig } @@ -358,7 +358,7 @@ 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(atmosConfig, err) + u.LogErrorAndExit(err) } // If the command to get the value for the ENV var is provided, execute it @@ -366,28 +366,28 @@ func executeCustomCommand( valCommandName := fmt.Sprintf("env-var-%s-valcommand", key) res, err := e.ExecuteShellAndReturnOutput(atmosConfig, valCommand, valCommandName, ".", nil, false) if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(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(atmosConfig, err) + u.LogErrorAndExit(err) } } envVarsList = append(envVarsList, fmt.Sprintf("%s=%s", key, value)) err = os.Setenv(key, value) if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } } if len(envVarsList) > 0 && commandConfig.Verbose { - u.LogDebug(atmosConfig, "\nUsing ENV vars:") + u.LogDebug("\nUsing ENV vars:") for _, v := range envVarsList { - u.LogDebug(atmosConfig, v) + u.LogDebug(v) } } @@ -395,14 +395,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(atmosConfig, err) + u.LogErrorAndExit(err) } // Execute the command step commandName := fmt.Sprintf("%s-step-%d", commandConfig.Name, i) err = e.ExecuteShell(atmosConfig, commandToRun, commandName, ".", envVarsList, false) if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } } } @@ -435,7 +435,7 @@ func checkAtmosConfig(opts ...AtmosValidateOption) { atmosConfig, err := cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, false) if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } if vCfg.CheckStack { @@ -455,7 +455,7 @@ func printMessageForMissingAtmosConfig(atmosConfig schema.AtmosConfiguration) { fmt.Println() err := tuiUtils.PrintStyledText("ATMOS") if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } if atmosConfig.Default { @@ -501,7 +501,7 @@ func CheckForAtmosUpdateAndPrintMessage(atmosConfig schema.AtmosConfiguration) { // Load the cache cacheCfg, err := cfg.LoadCache() if err != nil { - u.LogWarning(atmosConfig, fmt.Sprintf("Could not load cache: %s", err)) + u.LogWarning(fmt.Sprintf("Could not load cache: %s", err)) return } @@ -514,12 +514,12 @@ func CheckForAtmosUpdateAndPrintMessage(atmosConfig schema.AtmosConfiguration) { // Get the latest Atmos release from GitHub latestReleaseTag, err := u.GetLatestGitHubRepoRelease("cloudposse", "atmos") if err != nil { - u.LogWarning(atmosConfig, fmt.Sprintf("Failed to retrieve latest Atmos release info: %s", err)) + u.LogWarning(fmt.Sprintf("Failed to retrieve latest Atmos release info: %s", err)) return } if latestReleaseTag == "" { - u.LogWarning(atmosConfig, "No release information available") + u.LogWarning("No release information available") return } @@ -535,8 +535,7 @@ func CheckForAtmosUpdateAndPrintMessage(atmosConfig schema.AtmosConfiguration) { // Update the cache to mark the current timestamp cacheCfg.LastChecked = time.Now().Unix() if saveErr := cfg.SaveCache(cacheCfg); saveErr != nil { - u.LogWarning(atmosConfig, fmt.Sprintf("Unable to save cache: %s", saveErr)) - + u.LogWarning(fmt.Sprintf("Unable to save cache: %s", saveErr)) } } @@ -554,7 +553,6 @@ func handleHelpRequest(cmd *cobra.Command, args []string) { } func showUsageAndExit(cmd *cobra.Command, args []string) { - var suggestions []string unknownCommand := fmt.Sprintf("Error: Unknown command: %q\n\n", cmd.CommandPath()) @@ -593,7 +591,7 @@ func getConfigAndStacksInfo(commandName string, cmd *cobra.Command, args []strin checkAtmosConfig() var argsAfterDoubleDash []string - var finalArgs = args + finalArgs := args doubleDashIndex := lo.IndexOf(args, "--") if doubleDashIndex > 0 { @@ -603,7 +601,7 @@ func getConfigAndStacksInfo(commandName string, cmd *cobra.Command, args []strin info, err := e.ProcessCommandLineArgs(commandName, cmd, finalArgs, argsAfterDoubleDash) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } return info } diff --git a/cmd/completion.go b/cmd/completion.go index 93375e578..e6e26a422 100644 --- a/cmd/completion.go +++ b/cmd/completion.go @@ -31,7 +31,7 @@ func runCompletion(cmd *cobra.Command, args []string) { } if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } } diff --git a/cmd/describe_affected.go b/cmd/describe_affected.go index c32337923..7227e4d9b 100644 --- a/cmd/describe_affected.go +++ b/cmd/describe_affected.go @@ -1,7 +1,6 @@ package cmd import ( - "github.com/cloudposse/atmos/pkg/schema" "github.com/spf13/cobra" e "github.com/cloudposse/atmos/internal/exec" @@ -21,7 +20,7 @@ var describeAffectedCmd = &cobra.Command{ err := e.ExecuteDescribeAffectedCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } }, } diff --git a/cmd/describe_component.go b/cmd/describe_component.go index d6eea1317..20051b8b9 100644 --- a/cmd/describe_component.go +++ b/cmd/describe_component.go @@ -1,7 +1,6 @@ package cmd import ( - "github.com/cloudposse/atmos/pkg/schema" "github.com/spf13/cobra" e "github.com/cloudposse/atmos/internal/exec" @@ -20,7 +19,7 @@ var describeComponentCmd = &cobra.Command{ err := e.ExecuteDescribeComponentCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } }, } @@ -34,7 +33,7 @@ func init() { err := describeComponentCmd.MarkPersistentFlagRequired("stack") if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } describeCmd.AddCommand(describeComponentCmd) diff --git a/cmd/describe_config.go b/cmd/describe_config.go index e258e7d4c..1a683f394 100644 --- a/cmd/describe_config.go +++ b/cmd/describe_config.go @@ -4,7 +4,6 @@ import ( "github.com/spf13/cobra" e "github.com/cloudposse/atmos/internal/exec" - "github.com/cloudposse/atmos/pkg/schema" u "github.com/cloudposse/atmos/pkg/utils" ) @@ -16,10 +15,9 @@ var describeConfigCmd = &cobra.Command{ FParseErrWhitelist: struct{ UnknownFlags bool }{UnknownFlags: false}, Args: cobra.NoArgs, Run: func(cmd *cobra.Command, args []string) { - err := e.ExecuteDescribeConfigCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } }, } diff --git a/cmd/describe_dependents.go b/cmd/describe_dependents.go index ca50fd9d4..bb25f2840 100644 --- a/cmd/describe_dependents.go +++ b/cmd/describe_dependents.go @@ -1,7 +1,6 @@ package cmd import ( - "github.com/cloudposse/atmos/pkg/schema" "github.com/spf13/cobra" e "github.com/cloudposse/atmos/internal/exec" @@ -21,7 +20,7 @@ var describeDependentsCmd = &cobra.Command{ err := e.ExecuteDescribeDependentsCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } }, } @@ -35,7 +34,7 @@ func init() { err := describeDependentsCmd.MarkPersistentFlagRequired("stack") if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } describeCmd.AddCommand(describeDependentsCmd) diff --git a/cmd/describe_stacks.go b/cmd/describe_stacks.go index f6bc1287a..5f0541a62 100644 --- a/cmd/describe_stacks.go +++ b/cmd/describe_stacks.go @@ -95,6 +95,7 @@ var describeStacksCmd = &cobra.Command{ u.PrintMessageInColor(output, theme.Colors.Success) } else { fmt.Println(output) + u.LogErrorAndExit(err) } }, } diff --git a/cmd/describe_workflows.go b/cmd/describe_workflows.go index 855af276f..8b5f79758 100644 --- a/cmd/describe_workflows.go +++ b/cmd/describe_workflows.go @@ -4,7 +4,6 @@ import ( "github.com/spf13/cobra" e "github.com/cloudposse/atmos/internal/exec" - "github.com/cloudposse/atmos/pkg/schema" u "github.com/cloudposse/atmos/pkg/utils" ) @@ -25,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.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } }, } diff --git a/cmd/docs.go b/cmd/docs.go index b4f1a8b7b..b7ab8dbe4 100644 --- a/cmd/docs.go +++ b/cmd/docs.go @@ -36,7 +36,7 @@ var docsCmd = &cobra.Command{ atmosConfig, err := cfg.InitCliConfig(info, true) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } // Detect terminal width if not specified in `atmos.yaml` @@ -44,7 +44,7 @@ var docsCmd = &cobra.Command{ maxWidth := atmosConfig.Settings.Terminal.MaxWidth if maxWidth == 0 && atmosConfig.Settings.Docs.MaxWidth > 0 { maxWidth = atmosConfig.Settings.Docs.MaxWidth - u.LogWarning(atmosConfig, "'settings.docs.max-width' is deprecated and will be removed in a future version. Please use 'settings.terminal.max_width' instead") + u.LogWarning("'settings.docs.max-width' is deprecated and will be removed in a future version. Please use 'settings.terminal.max_width' instead") } defaultWidth := 120 screenWidth := defaultWidth @@ -66,24 +66,24 @@ var docsCmd = &cobra.Command{ componentPath := filepath.Join(atmosConfig.BasePath, atmosConfig.Components.Terraform.BasePath, info.Component) componentPathExists, err := u.IsDirectory(componentPath) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } if !componentPathExists { - u.LogErrorAndExit(schema.AtmosConfiguration{}, fmt.Errorf("Component '%s' not found in path: '%s'", info.Component, componentPath)) + u.LogErrorAndExit(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.AtmosConfiguration{}, fmt.Errorf("No README found for component: %s", info.Component)) + u.LogErrorAndExit(fmt.Errorf("No README found for component: %s", info.Component)) } else { - u.LogErrorAndExit(schema.AtmosConfiguration{}, fmt.Errorf("Component %s not found", info.Component)) + u.LogErrorAndExit(fmt.Errorf("Component %s not found", info.Component)) } } readmeContent, err := os.ReadFile(readmePath) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } r, err := glamour.NewTermRenderer( @@ -93,22 +93,22 @@ var docsCmd = &cobra.Command{ glamour.WithWordWrap(screenWidth), ) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, fmt.Errorf("failed to initialize markdown renderer: %w", err)) + u.LogErrorAndExit(fmt.Errorf("failed to initialize markdown renderer: %w", err)) } componentDocs, err := r.Render(string(readmeContent)) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } pager := atmosConfig.Settings.Terminal.Pager if !pager && atmosConfig.Settings.Docs.Pagination { pager = atmosConfig.Settings.Docs.Pagination - u.LogWarning(atmosConfig, "'settings.docs.pagination' is deprecated and will be removed in a future version. Please use 'settings.terminal.pager' instead") + u.LogWarning("'settings.docs.pagination' is deprecated and will be removed in a future version. Please use 'settings.terminal.pager' instead") } if err := u.DisplayDocs(componentDocs, pager); err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, fmt.Errorf("failed to display documentation: %w", err)) + u.LogErrorAndExit(fmt.Errorf("failed to display documentation: %w", err)) } return @@ -118,7 +118,7 @@ var docsCmd = &cobra.Command{ var err error if os.Getenv("GO_TEST") == "1" { - u.LogDebug(atmosConfig, "Skipping browser launch in test environment") + u.LogDebug("Skipping browser launch in test environment") return // Skip launching the browser } @@ -134,7 +134,7 @@ var docsCmd = &cobra.Command{ } if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } }, } diff --git a/cmd/helmfile.go b/cmd/helmfile.go index 0c62ba872..7f381d441 100644 --- a/cmd/helmfile.go +++ b/cmd/helmfile.go @@ -30,6 +30,6 @@ func helmfileRun(cmd *cobra.Command, commandName string, args []string) { info := getConfigAndStacksInfo("helmfile", cmd, diffArgs) err := e.ExecuteHelmfile(info) if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } } diff --git a/cmd/helmfile_generate_varfile.go b/cmd/helmfile_generate_varfile.go index acaac887e..2ed7a568c 100644 --- a/cmd/helmfile_generate_varfile.go +++ b/cmd/helmfile_generate_varfile.go @@ -4,7 +4,6 @@ import ( "github.com/spf13/cobra" e "github.com/cloudposse/atmos/internal/exec" - "github.com/cloudposse/atmos/pkg/schema" u "github.com/cloudposse/atmos/pkg/utils" ) @@ -21,7 +20,7 @@ var helmfileGenerateVarfileCmd = &cobra.Command{ err := e.ExecuteHelmfileGenerateVarfileCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } }, } @@ -33,7 +32,7 @@ func init() { err := helmfileGenerateVarfileCmd.MarkPersistentFlagRequired("stack") if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } helmfileGenerateCmd.AddCommand(helmfileGenerateVarfileCmd) diff --git a/cmd/pro_lock.go b/cmd/pro_lock.go index 68191669f..925f2987a 100644 --- a/cmd/pro_lock.go +++ b/cmd/pro_lock.go @@ -4,7 +4,6 @@ import ( "github.com/spf13/cobra" e "github.com/cloudposse/atmos/internal/exec" - "github.com/cloudposse/atmos/pkg/schema" u "github.com/cloudposse/atmos/pkg/utils" ) @@ -21,7 +20,7 @@ var proLockCmd = &cobra.Command{ err := e.ExecuteProLockCommand(cmd, args) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } }, } diff --git a/cmd/pro_unlock.go b/cmd/pro_unlock.go index feb625a60..1dd0ef9a1 100644 --- a/cmd/pro_unlock.go +++ b/cmd/pro_unlock.go @@ -4,7 +4,6 @@ import ( "github.com/spf13/cobra" e "github.com/cloudposse/atmos/internal/exec" - "github.com/cloudposse/atmos/pkg/schema" u "github.com/cloudposse/atmos/pkg/utils" ) @@ -21,7 +20,7 @@ var proUnlockCmd = &cobra.Command{ err := e.ExecuteProUnlockCommand(cmd, args) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } }, } diff --git a/cmd/root.go b/cmd/root.go index b47caf842..683a57ead 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -3,10 +3,12 @@ package cmd import ( "errors" "fmt" + "io" "os" "regexp" "strings" + "github.com/charmbracelet/log" "github.com/elewis787/boa" "github.com/spf13/cobra" @@ -47,13 +49,6 @@ var RootCmd = &cobra.Command{ logsLevel, _ := cmd.Flags().GetString("logs-level") logsFile, _ := cmd.Flags().GetString("logs-file") - errorConfig := schema.AtmosConfiguration{ - Logs: schema.Logs{ - Level: logsLevel, - File: logsFile, - }, - } - configAndStacksInfo := schema.ConfigAndStacksInfo{ LogsLevel: logsLevel, LogsFile: logsFile, @@ -65,10 +60,10 @@ var RootCmd = &cobra.Command{ if errors.Is(err, cfg.NotFound) { // For help commands or when help flag is set, we don't want to show the error if !isHelpRequested { - u.LogWarning(errorConfig, err.Error()) + u.LogWarning(err.Error()) } } else { - u.LogErrorAndExit(errorConfig, err) + u.LogErrorAndExit(err) } } }, @@ -80,16 +75,42 @@ var RootCmd = &cobra.Command{ fmt.Println() err := tuiUtils.PrintStyledText("ATMOS") if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } err = e.ExecuteAtmosCmd() if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } }, } +func setupLogger(atmosConfig *schema.AtmosConfiguration) { + switch atmosConfig.Logs.Level { + case "Trace": + log.SetLevel(log.DebugLevel) + case "Debug": + log.SetLevel(log.DebugLevel) + case "Info": + log.SetLevel(log.InfoLevel) + case "Warning": + log.SetLevel(log.WarnLevel) + case "Off": + log.SetOutput(io.Discard) + default: + log.SetLevel(log.InfoLevel) + } + + if atmosConfig.Logs.File != "/dev/stderr" { + logFile, err := os.OpenFile(atmosConfig.Logs.File, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o666) + if err != nil { + log.Fatal("Failed to open log file:", err) + } + defer logFile.Close() + log.SetOutput(logFile) + } +} + // Execute adds all child commands to the root command and sets flags appropriately. // This is called by main.main(). It only needs to happen once to the RootCmd. func Execute() error { @@ -104,22 +125,26 @@ func Execute() error { atmosConfig, initErr = cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, false) if initErr != nil && !errors.Is(initErr, cfg.NotFound) { if isVersionCommand() { - u.LogTrace(schema.AtmosConfiguration{}, fmt.Sprintf("warning: CLI configuration 'atmos.yaml' file not found. Error: %s", initErr)) + log.Debug("warning: CLI configuration 'atmos.yaml' file not found", "error", initErr) } else { - u.LogErrorAndExit(schema.AtmosConfiguration{}, initErr) + u.LogErrorAndExit(initErr) } } + + // Set the log level for the charmbracelet/log package based on the atmosConfig + setupLogger(&atmosConfig) + var err error // If CLI configuration was found, process its custom commands and command aliases if initErr == nil { err = processCustomCommands(atmosConfig, atmosConfig.Commands, RootCmd, true) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } err = processCommandAliases(atmosConfig, atmosConfig.CommandAliases, RootCmd, true) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } } @@ -165,7 +190,7 @@ func init() { // Set custom usage template err := templates.SetCustomUsageFunc(RootCmd) if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } initCobraConfig() @@ -196,19 +221,19 @@ func initCobraConfig() { if command.Use != "atmos" || command.Flags().Changed("help") { err := tuiUtils.PrintStyledText("ATMOS") if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } if err := oldUsageFunc(command); err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } } else { err := tuiUtils.PrintStyledText("ATMOS") if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } b.HelpFunc(command, args) if err := command.Usage(); err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } } CheckForAtmosUpdateAndPrintMessage(atmosConfig) diff --git a/cmd/terraform.go b/cmd/terraform.go index d190d426a..c016b40fa 100644 --- a/cmd/terraform.go +++ b/cmd/terraform.go @@ -43,7 +43,7 @@ func terraformRun(cmd *cobra.Command, actualCmd *cobra.Command, args []string) { } err := e.ExecuteTerraform(info) if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } } diff --git a/cmd/terraform_generate_backend.go b/cmd/terraform_generate_backend.go index d65f9ddd4..8a5bdf3fc 100644 --- a/cmd/terraform_generate_backend.go +++ b/cmd/terraform_generate_backend.go @@ -4,7 +4,6 @@ import ( "github.com/spf13/cobra" e "github.com/cloudposse/atmos/internal/exec" - "github.com/cloudposse/atmos/pkg/schema" u "github.com/cloudposse/atmos/pkg/utils" ) @@ -22,7 +21,7 @@ var terraformGenerateBackendCmd = &cobra.Command{ err := e.ExecuteTerraformGenerateBackendCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } }, } @@ -33,7 +32,7 @@ func init() { err := terraformGenerateBackendCmd.MarkPersistentFlagRequired("stack") if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } terraformGenerateCmd.AddCommand(terraformGenerateBackendCmd) diff --git a/cmd/terraform_generate_backends.go b/cmd/terraform_generate_backends.go index 8f9f11f6d..997028ae3 100644 --- a/cmd/terraform_generate_backends.go +++ b/cmd/terraform_generate_backends.go @@ -4,7 +4,6 @@ import ( "github.com/spf13/cobra" e "github.com/cloudposse/atmos/internal/exec" - "github.com/cloudposse/atmos/pkg/schema" u "github.com/cloudposse/atmos/pkg/utils" ) @@ -21,7 +20,7 @@ var terraformGenerateBackendsCmd = &cobra.Command{ err := e.ExecuteTerraformGenerateBackendsCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } }, } diff --git a/cmd/terraform_generate_varfile.go b/cmd/terraform_generate_varfile.go index 6d1fa2327..610bb3507 100644 --- a/cmd/terraform_generate_varfile.go +++ b/cmd/terraform_generate_varfile.go @@ -4,7 +4,6 @@ import ( "github.com/spf13/cobra" e "github.com/cloudposse/atmos/internal/exec" - "github.com/cloudposse/atmos/pkg/schema" u "github.com/cloudposse/atmos/pkg/utils" ) @@ -21,7 +20,7 @@ var terraformGenerateVarfileCmd = &cobra.Command{ err := e.ExecuteTerraformGenerateVarfileCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } }, } @@ -33,7 +32,7 @@ func init() { err := terraformGenerateVarfileCmd.MarkPersistentFlagRequired("stack") if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } terraformGenerateCmd.AddCommand(terraformGenerateVarfileCmd) diff --git a/cmd/terraform_generate_varfiles.go b/cmd/terraform_generate_varfiles.go index 25e756454..dba3bbaa4 100644 --- a/cmd/terraform_generate_varfiles.go +++ b/cmd/terraform_generate_varfiles.go @@ -4,7 +4,6 @@ import ( "github.com/spf13/cobra" e "github.com/cloudposse/atmos/internal/exec" - "github.com/cloudposse/atmos/pkg/schema" u "github.com/cloudposse/atmos/pkg/utils" ) @@ -21,7 +20,7 @@ var terraformGenerateVarfilesCmd = &cobra.Command{ err := e.ExecuteTerraformGenerateVarfilesCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } }, } @@ -59,7 +58,7 @@ func init() { err := terraformGenerateVarfilesCmd.MarkPersistentFlagRequired("file-template") if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } terraformGenerateCmd.AddCommand(terraformGenerateVarfilesCmd) diff --git a/cmd/validate_component.go b/cmd/validate_component.go index ece24430d..c351c8fff 100644 --- a/cmd/validate_component.go +++ b/cmd/validate_component.go @@ -6,7 +6,6 @@ import ( "github.com/spf13/cobra" e "github.com/cloudposse/atmos/internal/exec" - "github.com/cloudposse/atmos/pkg/schema" "github.com/cloudposse/atmos/pkg/ui/theme" u "github.com/cloudposse/atmos/pkg/utils" ) @@ -27,7 +26,7 @@ var validateComponentCmd = &cobra.Command{ component, stack, err := e.ExecuteValidateComponentCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } m := fmt.Sprintf("component '%s' in stack '%s' validated successfully\n", component, stack) @@ -46,7 +45,7 @@ func init() { err := validateComponentCmd.MarkPersistentFlagRequired("stack") if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } validateCmd.AddCommand(validateComponentCmd) diff --git a/cmd/validate_editorconfig.go b/cmd/validate_editorconfig.go index 6aa77365f..7b23717b1 100644 --- a/cmd/validate_editorconfig.go +++ b/cmd/validate_editorconfig.go @@ -49,7 +49,7 @@ var editorConfigCmd *cobra.Command = &cobra.Command{ func initializeConfig(cmd *cobra.Command) { replaceAtmosConfigInConfig(cmd, atmosConfig) - var configPaths = []string{} + configPaths := []string{} if configFilePath == "" { configPaths = append(configPaths, defaultConfigFileNames[:]...) } else { @@ -61,7 +61,7 @@ func initializeConfig(cmd *cobra.Command) { if initEditorConfig { err := currentConfig.Save(version.Version) if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } } @@ -93,13 +93,13 @@ func replaceAtmosConfigInConfig(cmd *cobra.Command, atmosConfig schema.AtmosConf if !cmd.Flags().Changed("format") && atmosConfig.Validate.EditorConfig.Format != "" { format := outputformat.OutputFormat(atmosConfig.Validate.EditorConfig.Format) if ok := format.IsValid(); !ok { - u.LogErrorAndExit(atmosConfig, fmt.Errorf("%v is not a valid format choose from the following: %v", atmosConfig.Validate.EditorConfig.Format, outputformat.GetArgumentChoiceText())) + u.LogErrorAndExit(fmt.Errorf("%v is not a valid format choose from the following: %v", atmosConfig.Validate.EditorConfig.Format, outputformat.GetArgumentChoiceText())) } cliConfig.Format = format } else if cmd.Flags().Changed("format") { format := outputformat.OutputFormat(format) if ok := format.IsValid(); !ok { - u.LogErrorAndExit(atmosConfig, fmt.Errorf("%v is not a valid format choose from the following: %v", atmosConfig.Validate.EditorConfig.Format, outputformat.GetArgumentChoiceText())) + u.LogErrorAndExit(fmt.Errorf("%v is not a valid format choose from the following: %v", atmosConfig.Validate.EditorConfig.Format, outputformat.GetArgumentChoiceText())) } cliConfig.Format = format } @@ -136,27 +136,27 @@ func replaceAtmosConfigInConfig(cmd *cobra.Command, atmosConfig schema.AtmosConf // runMainLogic contains the main logic func runMainLogic() { config := *currentConfig - u.LogDebug(atmosConfig, config.String()) - u.LogTrace(atmosConfig, fmt.Sprintf("Exclude Regexp: %s", config.GetExcludesAsRegularExpression())) + u.LogDebug(config.String()) + u.LogTrace(fmt.Sprintf("Exclude Regexp: %s", config.GetExcludesAsRegularExpression())) if err := checkVersion(config); err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } filePaths, err := files.GetFiles(config) if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } if config.DryRun { for _, file := range filePaths { - u.LogInfo(atmosConfig, file) + u.LogInfo(file) } os.Exit(0) } errors := validation.ProcessValidation(filePaths, config) - u.LogDebug(atmosConfig, fmt.Sprintf("%d files checked", len(filePaths))) + u.LogDebug(fmt.Sprintf("%d files checked", len(filePaths))) errorCount := er.GetErrorCount(errors) if errorCount != 0 { er.PrintErrors(errors, config) diff --git a/cmd/validate_stacks.go b/cmd/validate_stacks.go index ef8cdb210..fa48e43d6 100644 --- a/cmd/validate_stacks.go +++ b/cmd/validate_stacks.go @@ -4,7 +4,6 @@ import ( "github.com/spf13/cobra" e "github.com/cloudposse/atmos/internal/exec" - "github.com/cloudposse/atmos/pkg/schema" "github.com/cloudposse/atmos/pkg/ui/theme" u "github.com/cloudposse/atmos/pkg/utils" ) @@ -23,7 +22,7 @@ var ValidateStacksCmd = &cobra.Command{ err := e.ExecuteValidateStacksCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } u.PrintMessageInColor("all stacks validated successfully\n", theme.Colors.Success) diff --git a/cmd/vendor_diff.go b/cmd/vendor_diff.go index f208c98d8..3fd666c57 100644 --- a/cmd/vendor_diff.go +++ b/cmd/vendor_diff.go @@ -4,7 +4,6 @@ import ( "github.com/spf13/cobra" e "github.com/cloudposse/atmos/internal/exec" - "github.com/cloudposse/atmos/pkg/schema" u "github.com/cloudposse/atmos/pkg/utils" ) @@ -23,7 +22,7 @@ var vendorDiffCmd = &cobra.Command{ err := e.ExecuteVendorDiffCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } }, } diff --git a/cmd/vendor_pull.go b/cmd/vendor_pull.go index f860c556f..55c5eb4b3 100644 --- a/cmd/vendor_pull.go +++ b/cmd/vendor_pull.go @@ -4,7 +4,6 @@ import ( "github.com/spf13/cobra" e "github.com/cloudposse/atmos/internal/exec" - "github.com/cloudposse/atmos/pkg/schema" u "github.com/cloudposse/atmos/pkg/utils" ) @@ -22,7 +21,7 @@ var vendorPullCmd = &cobra.Command{ err := e.ExecuteVendorPullCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } }, } diff --git a/cmd/version.go b/cmd/version.go index 4007acaf8..98deea572 100644 --- a/cmd/version.go +++ b/cmd/version.go @@ -8,7 +8,6 @@ import ( "github.com/spf13/cobra" tuiUtils "github.com/cloudposse/atmos/internal/tui/utils" - "github.com/cloudposse/atmos/pkg/schema" u "github.com/cloudposse/atmos/pkg/utils" "github.com/cloudposse/atmos/pkg/version" ) @@ -26,7 +25,7 @@ var versionCmd = &cobra.Command{ fmt.Println() err := tuiUtils.PrintStyledText("ATMOS") if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } atmosIcon := "\U0001F47D" @@ -39,11 +38,11 @@ var versionCmd = &cobra.Command{ latestReleaseTag, err := u.GetLatestGitHubRepoRelease("cloudposse", "atmos") if err == nil && latestReleaseTag != "" { if err != nil { - u.LogWarning(schema.AtmosConfiguration{}, fmt.Sprintf("Failed to check for updates: %v", err)) + u.LogWarning(fmt.Sprintf("Failed to check for updates: %v", err)) return } if latestReleaseTag == "" { - u.LogWarning(schema.AtmosConfiguration{}, "No release information available") + u.LogWarning("No release information available") return } latestRelease := strings.TrimPrefix(latestReleaseTag, "v") diff --git a/cmd/workflow.go b/cmd/workflow.go index 434287417..465ed6e5d 100644 --- a/cmd/workflow.go +++ b/cmd/workflow.go @@ -88,7 +88,7 @@ var workflowCmd = &cobra.Command{ if len(args) == 0 { err := e.ExecuteWorkflowCmd(cmd, args) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } return } @@ -101,7 +101,7 @@ var workflowCmd = &cobra.Command{ // Get atmos configuration atmosConfig, err := cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, false) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, fmt.Errorf("failed to initialize atmos config: %w", err)) + u.LogErrorAndExit(fmt.Errorf("failed to initialize atmos config: %w", err)) } // Create a terminal writer to get the optimal width @@ -116,7 +116,7 @@ var workflowCmd = &cobra.Command{ markdown.WithWidth(screenWidth), ) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, fmt.Errorf("failed to create markdown renderer: %w", err)) + u.LogErrorAndExit(fmt.Errorf("failed to create markdown renderer: %w", err)) } // Generate the error message dynamically using H1 styling @@ -124,7 +124,7 @@ var workflowCmd = &cobra.Command{ content := errorMsg + workflowMarkdown rendered, err := renderer.Render(content) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, fmt.Errorf("failed to render markdown: %w", err)) + u.LogErrorAndExit(fmt.Errorf("failed to render markdown: %w", err)) } // Remove duplicate URLs and format output @@ -162,7 +162,7 @@ var workflowCmd = &cobra.Command{ Suggestion: suggestion, }) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } } else if strings.Contains(err.Error(), "does not have the") { details, suggestion := getMarkdownSection("Invalid Workflow") @@ -172,11 +172,11 @@ var workflowCmd = &cobra.Command{ Suggestion: suggestion, }) if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } } else { // For other errors, use the standard error handler - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } return } diff --git a/internal/exec/atlantis_generate_repo_config.go b/internal/exec/atlantis_generate_repo_config.go index d833740e9..b1a745053 100644 --- a/internal/exec/atlantis_generate_repo_config.go +++ b/internal/exec/atlantis_generate_repo_config.go @@ -227,7 +227,6 @@ func ExecuteAtlantisGenerateRepoConfig( stacks []string, components []string, ) error { - stacksMap, _, err := FindStacksMap(atmosConfig, false) if err != nil { return err @@ -487,14 +486,14 @@ func ExecuteAtlantisGenerateRepoConfig( fileName := outputPath if fileName == "" { fileName = atmosConfig.Integrations.Atlantis.Path - u.LogDebug(atmosConfig, fmt.Sprintf("Using 'atlantis.path: %s' from 'atmos.yaml'", fileName)) + u.LogDebug(fmt.Sprintf("Using 'atlantis.path: %s' from 'atmos.yaml'", fileName)) } else { - u.LogDebug(atmosConfig, fmt.Sprintf("Using '--output-path %s' command-line argument", fileName)) + u.LogDebug(fmt.Sprintf("Using '--output-path %s' command-line argument", fileName)) } // If the path is empty, dump to 'stdout' if fileName != "" { - u.LogDebug(atmosConfig, fmt.Sprintf("Writing atlantis repo config file to '%s'\n", fileName)) + u.LogDebug(fmt.Sprintf("Writing atlantis repo config file to '%s'\n", fileName)) fileAbsolutePath, err := filepath.Abs(fileName) if err != nil { @@ -507,7 +506,7 @@ func ExecuteAtlantisGenerateRepoConfig( return err } - err = u.WriteToFileAsYAML(fileAbsolutePath, atlantisYaml, 0644) + err = u.WriteToFileAsYAML(fileAbsolutePath, atlantisYaml, 0o644) if err != nil { return err } diff --git a/internal/exec/aws_eks_update_kubeconfig.go b/internal/exec/aws_eks_update_kubeconfig.go index eae912ac3..a739948bc 100644 --- a/internal/exec/aws_eks_update_kubeconfig.go +++ b/internal/exec/aws_eks_update_kubeconfig.go @@ -231,7 +231,7 @@ func ExecuteAwsEksUpdateKubeconfig(kubeconfigContext schema.AwsEksUpdateKubeconf 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(atmosConfig, message) + u.LogDebug(message) } return nil diff --git a/internal/exec/describe_affected_utils.go b/internal/exec/describe_affected_utils.go index 1beb370d8..9fd339db3 100644 --- a/internal/exec/describe_affected_utils.go +++ b/internal/exec/describe_affected_utils.go @@ -41,7 +41,6 @@ func ExecuteDescribeAffectedWithTargetRefClone( includeSettings bool, stack string, ) ([]schema.Affected, *plumbing.Reference, *plumbing.Reference, string, error) { - if verbose { atmosConfig.Logs.Level = u.LogLevelTrace } @@ -73,7 +72,7 @@ func ExecuteDescribeAffectedWithTargetRefClone( defer removeTempDir(atmosConfig, tempDir) - u.LogTrace(atmosConfig, fmt.Sprintf("\nCloning repo '%s' into the temp dir '%s'", localRepoInfo.RepoUrl, tempDir)) + u.LogTrace(fmt.Sprintf("\nCloning repo '%s' into the temp dir '%s'", localRepoInfo.RepoUrl, tempDir)) cloneOptions := git.CloneOptions{ URL: localRepoInfo.RepoUrl, @@ -84,9 +83,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(atmosConfig, fmt.Sprintf("\nCloning Git ref '%s' ...\n", ref)) + u.LogTrace(fmt.Sprintf("\nCloning Git ref '%s' ...\n", ref)) } else { - u.LogTrace(atmosConfig, "\nCloned the HEAD of the default branch ...\n") + u.LogTrace("\nCloned the HEAD of the default branch ...\n") } if verbose { @@ -126,14 +125,14 @@ func ExecuteDescribeAffectedWithTargetRefClone( } if ref != "" { - u.LogTrace(atmosConfig, fmt.Sprintf("\nCloned Git ref '%s'\n", ref)) + u.LogTrace(fmt.Sprintf("\nCloned Git ref '%s'\n", ref)) } else { - u.LogTrace(atmosConfig, fmt.Sprintf("\nCloned Git ref '%s'\n", remoteRepoHead.Name())) + u.LogTrace(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(atmosConfig, fmt.Sprintf("\nChecking out commit SHA '%s' ...\n", sha)) + u.LogTrace(fmt.Sprintf("\nChecking out commit SHA '%s' ...\n", sha)) w, err := remoteRepo.Worktree() if err != nil { @@ -152,7 +151,7 @@ func ExecuteDescribeAffectedWithTargetRefClone( return nil, nil, nil, "", err } - u.LogTrace(atmosConfig, fmt.Sprintf("\nChecked out commit SHA '%s'\n", sha)) + u.LogTrace(fmt.Sprintf("\nChecked out commit SHA '%s'\n", sha)) } affected, localRepoHead, remoteRepoHead, err := executeDescribeAffected( @@ -184,7 +183,6 @@ func ExecuteDescribeAffectedWithTargetRefCheckout( includeSettings bool, stack string, ) ([]schema.Affected, *plumbing.Reference, *plumbing.Reference, string, error) { - if verbose { atmosConfig.Logs.Level = u.LogLevelTrace } @@ -208,7 +206,7 @@ func ExecuteDescribeAffectedWithTargetRefCheckout( defer removeTempDir(atmosConfig, tempDir) // Copy the local repo into the temp directory - u.LogTrace(atmosConfig, fmt.Sprintf("\nCopying the local repo into the temp directory '%s' ...", tempDir)) + u.LogTrace(fmt.Sprintf("\nCopying the local repo into the temp directory '%s' ...", tempDir)) copyOptions := cp.Options{ PreserveTimes: false, @@ -236,7 +234,7 @@ func ExecuteDescribeAffectedWithTargetRefCheckout( return nil, nil, nil, "", err } - u.LogTrace(atmosConfig, fmt.Sprintf("Copied the local repo into the temp directory '%s'\n", tempDir)) + u.LogTrace(fmt.Sprintf("Copied the local repo into the temp directory '%s'\n", tempDir)) remoteRepo, err := git.PlainOpenWithOptions(tempDir, &git.PlainOpenOptions{ DetectDotGit: false, @@ -253,7 +251,7 @@ func ExecuteDescribeAffectedWithTargetRefCheckout( } if sha != "" { - u.LogTrace(atmosConfig, fmt.Sprintf("\nChecking out commit SHA '%s' ...\n", sha)) + u.LogTrace(fmt.Sprintf("\nChecking out commit SHA '%s' ...\n", sha)) w, err := remoteRepo.Worktree() if err != nil { @@ -272,14 +270,14 @@ func ExecuteDescribeAffectedWithTargetRefCheckout( return nil, nil, nil, "", err } - u.LogTrace(atmosConfig, fmt.Sprintf("Checked out commit SHA '%s'\n", sha)) + u.LogTrace(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(atmosConfig, fmt.Sprintf("\nChecking out Git ref '%s' ...", ref)) + u.LogTrace(fmt.Sprintf("\nChecking out Git ref '%s' ...", ref)) w, err := remoteRepo.Worktree() if err != nil { @@ -304,7 +302,7 @@ func ExecuteDescribeAffectedWithTargetRefCheckout( return nil, nil, nil, "", err } - u.LogTrace(atmosConfig, fmt.Sprintf("Checked out Git ref '%s'\n", ref)) + u.LogTrace(fmt.Sprintf("Checked out Git ref '%s'\n", ref)) } affected, localRepoHead, remoteRepoHead, err := executeDescribeAffected( @@ -335,7 +333,6 @@ func ExecuteDescribeAffectedWithTargetRepoPath( includeSettings bool, stack string, ) ([]schema.Affected, *plumbing.Reference, *plumbing.Reference, string, error) { - localRepo, err := g.GetLocalRepo() if err != nil { return nil, nil, nil, "", err @@ -389,7 +386,6 @@ func executeDescribeAffected( includeSettings bool, stack string, ) ([]schema.Affected, *plumbing.Reference, *plumbing.Reference, error) { - if verbose { atmosConfig.Logs.Level = u.LogLevelTrace } @@ -404,8 +400,8 @@ func executeDescribeAffected( return nil, nil, nil, err } - u.LogTrace(atmosConfig, fmt.Sprintf("Current HEAD: %s", localRepoHead)) - u.LogTrace(atmosConfig, fmt.Sprintf("BASE: %s", remoteRepoHead)) + u.LogTrace(fmt.Sprintf("Current HEAD: %s", localRepoHead)) + u.LogTrace(fmt.Sprintf("BASE: %s", remoteRepoHead)) currentStacks, err := ExecuteDescribeStacks(atmosConfig, stack, nil, nil, nil, false, true, false) if err != nil { @@ -448,39 +444,39 @@ func executeDescribeAffected( return nil, nil, nil, err } - u.LogTrace(atmosConfig, fmt.Sprintf("\nGetting current working repo commit object...")) + u.LogTrace(fmt.Sprintf("\nGetting current working repo commit object...")) localCommit, err := localRepo.CommitObject(localRepoHead.Hash()) if err != nil { return nil, nil, nil, err } - u.LogTrace(atmosConfig, fmt.Sprintf("Got current working repo commit object")) - u.LogTrace(atmosConfig, fmt.Sprintf("Getting current working repo commit tree...")) + u.LogTrace(fmt.Sprintf("Got current working repo commit object")) + u.LogTrace(fmt.Sprintf("Getting current working repo commit tree...")) localTree, err := localCommit.Tree() if err != nil { return nil, nil, nil, err } - u.LogTrace(atmosConfig, fmt.Sprintf("Got current working repo commit tree")) - u.LogTrace(atmosConfig, fmt.Sprintf("Getting remote repo commit object...")) + u.LogTrace(fmt.Sprintf("Got current working repo commit tree")) + u.LogTrace(fmt.Sprintf("Getting remote repo commit object...")) remoteCommit, err := remoteRepo.CommitObject(remoteRepoHead.Hash()) if err != nil { return nil, nil, nil, err } - u.LogTrace(atmosConfig, fmt.Sprintf("Got remote repo commit object")) - u.LogTrace(atmosConfig, fmt.Sprintf("Getting remote repo commit tree...")) + u.LogTrace(fmt.Sprintf("Got remote repo commit object")) + u.LogTrace(fmt.Sprintf("Getting remote repo commit tree...")) remoteTree, err := remoteCommit.Tree() if err != nil { return nil, nil, nil, err } - 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 ...")) + u.LogTrace(fmt.Sprintf("Got remote repo commit tree")) + u.LogTrace(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) @@ -491,16 +487,16 @@ func executeDescribeAffected( var changedFiles []string if len(patch.Stats()) > 0 { - u.LogTrace(atmosConfig, fmt.Sprintf("Found difference between the current working branch and remote target branch")) - u.LogTrace(atmosConfig, "\nChanged files:\n") + u.LogTrace(fmt.Sprintf("Found difference between the current working branch and remote target branch")) + u.LogTrace("\nChanged files:\n") for _, fileStat := range patch.Stats() { - u.LogTrace(atmosConfig, fileStat.Name) + u.LogTrace(fileStat.Name) changedFiles = append(changedFiles, fileStat.Name) } - u.LogTrace(atmosConfig, "") + u.LogTrace("") } else { - u.LogTrace(atmosConfig, fmt.Sprintf("The current working branch and remote target branch are the same")) + u.LogTrace(fmt.Sprintf("The current working branch and remote target branch are the same")) } affected, err := findAffected( @@ -529,7 +525,6 @@ func findAffected( includeSettings bool, stackToFilter string, ) ([]schema.Affected, error) { - res := []schema.Affected{} var err error @@ -741,7 +736,6 @@ func findAffected( changedFiles, stackComponentSettings.DependsOn, ) - if err != nil { return nil, err } @@ -955,7 +949,6 @@ func findAffected( changedFiles, stackComponentSettings.DependsOn, ) - if err != nil { return nil, err } @@ -1018,7 +1011,6 @@ func appendToAffected( stacks map[string]any, includeSettings bool, ) ([]schema.Affected, error) { - // If the affected component in the stack was already added to the result, don't add it again for _, v := range affectedList { if v.Component == affected.Component && v.Stack == affected.Stack && v.ComponentType == affected.ComponentType { @@ -1101,7 +1093,6 @@ func isEqual( localSection map[string]any, sectionName string, ) bool { - if remoteStackSection, ok := remoteStacks[localStackName].(map[string]any); ok { if remoteComponentsSection, ok := remoteStackSection["components"].(map[string]any); ok { if remoteComponentTypeSection, ok := remoteComponentsSection[componentType].(map[string]any); ok { @@ -1123,7 +1114,6 @@ func isComponentDependentFolderOrFileChanged( changedFiles []string, deps schema.DependsOn, ) (bool, string, string, error) { - hasDependencies := false isChanged := false changedType := "" @@ -1184,7 +1174,6 @@ func isComponentFolderChanged( atmosConfig schema.AtmosConfiguration, changedFiles []string, ) (bool, error) { - var componentPath string switch componentType { @@ -1226,7 +1215,6 @@ func areTerraformComponentModulesChanged( atmosConfig schema.AtmosConfiguration, changedFiles []string, ) (bool, error) { - componentPath := filepath.Join(atmosConfig.BasePath, atmosConfig.Components.Terraform.BasePath, component) componentPathAbs, err := filepath.Abs(componentPath) @@ -1282,7 +1270,6 @@ func addAffectedSpaceliftAdminStack( configAndStacksInfo schema.ConfigAndStacksInfo, includeSettings bool, ) ([]schema.Affected, error) { - // Convert the `settings` section to the `Settings` structure var componentSettings schema.Settings err := mapstructure.Decode(settingsSection, &componentSettings) @@ -1525,7 +1512,7 @@ func processIncludedInDependenciesForDependents(dependents *[]schema.Dependent, func isComponentEnabled(metadataSection map[string]any, componentName string, atmosConfig schema.AtmosConfiguration) bool { if enabled, ok := metadataSection["enabled"].(bool); ok { if !enabled { - u.LogTrace(atmosConfig, fmt.Sprintf("Skipping disabled component %s", componentName)) + u.LogTrace(fmt.Sprintf("Skipping disabled component %s", componentName)) return false } } diff --git a/internal/exec/describe_stacks.go b/internal/exec/describe_stacks.go index b83baed17..4fa4d79e3 100644 --- a/internal/exec/describe_stacks.go +++ b/internal/exec/describe_stacks.go @@ -143,7 +143,6 @@ func ExecuteDescribeStacks( processTemplates bool, includeEmptyStacks bool, ) (map[string]any, error) { - stacksMap, _, err := FindStacksMap(atmosConfig, ignoreMissingFiles) if err != nil { return nil, err @@ -382,7 +381,7 @@ func ExecuteDescribeStacks( err = errors.Join(err, errors.New(errorMessage)) } } - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } componentSectionFinal, err := ProcessCustomYamlTags(atmosConfig, componentSectionConverted, stackName) @@ -573,7 +572,7 @@ func ExecuteDescribeStacks( err = errors.Join(err, errors.New(errorMessage)) } } - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } componentSectionFinal, err := ProcessCustomYamlTags(atmosConfig, componentSectionConverted, stackName) diff --git a/internal/exec/file_utils.go b/internal/exec/file_utils.go index 005b1d658..5ad88912f 100644 --- a/internal/exec/file_utils.go +++ b/internal/exec/file_utils.go @@ -16,14 +16,14 @@ import ( func removeTempDir(atmosConfig schema.AtmosConfiguration, path string) { err := os.RemoveAll(path) if err != nil { - u.LogWarning(atmosConfig, err.Error()) + u.LogWarning(err.Error()) } } func closeFile(fileName string, file io.ReadCloser) { err := file.Close() if err != nil { - u.LogError(schema.AtmosConfiguration{}, fmt.Errorf("error closing the file '%s': %v", fileName, err)) + u.LogError(fmt.Errorf("error closing the file '%s': %v", fileName, err)) } } @@ -42,7 +42,7 @@ func printOrWriteToFile( return err } } else { - err := u.WriteToFileAsYAML(file, data, 0644) + err := u.WriteToFileAsYAML(file, data, 0o644) if err != nil { return err } @@ -55,7 +55,7 @@ func printOrWriteToFile( return err } } else { - err := u.WriteToFileAsJSON(file, data, 0644) + err := u.WriteToFileAsJSON(file, data, 0o644) if err != nil { return err } diff --git a/internal/exec/go_getter_utils.go b/internal/exec/go_getter_utils.go index badfb3a67..4c6667d45 100644 --- a/internal/exec/go_getter_utils.go +++ b/internal/exec/go_getter_utils.go @@ -84,18 +84,18 @@ func (d *CustomGitHubDetector) Detect(src, _ string) (string, bool, error) { parsedURL, err := url.Parse(src) if err != nil { - u.LogDebug(d.AtmosConfig, fmt.Sprintf("Failed to parse URL %q: %v\n", src, err)) + u.LogDebug(fmt.Sprintf("Failed to parse URL %q: %v\n", src, err)) return "", false, fmt.Errorf("failed to parse URL %q: %w", src, err) } if strings.ToLower(parsedURL.Host) != "github.com" { - u.LogDebug(d.AtmosConfig, fmt.Sprintf("Host is %q, not 'github.com', skipping token injection\n", parsedURL.Host)) + u.LogDebug(fmt.Sprintf("Host is %q, not 'github.com', skipping token injection\n", parsedURL.Host)) return "", false, nil } parts := strings.SplitN(parsedURL.Path, "/", 4) if len(parts) < 3 { - u.LogDebug(d.AtmosConfig, fmt.Sprintf("URL path %q doesn't look like /owner/repo\n", parsedURL.Path)) + u.LogDebug(fmt.Sprintf("URL path %q doesn't look like /owner/repo\n", parsedURL.Path)) return "", false, fmt.Errorf("invalid GitHub URL %q", parsedURL.Path) } @@ -109,15 +109,15 @@ func (d *CustomGitHubDetector) Detect(src, _ string) (string, bool, error) { if atmosGitHubToken != "" { usedToken = atmosGitHubToken tokenSource = "ATMOS_GITHUB_TOKEN" - u.LogDebug(d.AtmosConfig, "ATMOS_GITHUB_TOKEN is set\n") + u.LogDebug("ATMOS_GITHUB_TOKEN is set\n") } else { // 2. Otherwise, only inject GITHUB_TOKEN if cfg.Settings.InjectGithubToken == true if d.AtmosConfig.Settings.InjectGithubToken && gitHubToken != "" { usedToken = gitHubToken tokenSource = "GITHUB_TOKEN" - u.LogTrace(d.AtmosConfig, "InjectGithubToken=true and GITHUB_TOKEN is set, using it\n") + u.LogTrace("InjectGithubToken=true and GITHUB_TOKEN is set, using it\n") } else { - u.LogTrace(d.AtmosConfig, "No ATMOS_GITHUB_TOKEN or GITHUB_TOKEN found\n") + u.LogTrace("No ATMOS_GITHUB_TOKEN or GITHUB_TOKEN found\n") } } @@ -125,10 +125,10 @@ func (d *CustomGitHubDetector) Detect(src, _ string) (string, bool, error) { user := parsedURL.User.Username() pass, _ := parsedURL.User.Password() if user == "" && pass == "" { - u.LogDebug(d.AtmosConfig, fmt.Sprintf("Injecting token from %s for %s\n", tokenSource, src)) + u.LogDebug(fmt.Sprintf("Injecting token from %s for %s\n", tokenSource, src)) parsedURL.User = url.UserPassword("x-access-token", usedToken) } else { - u.LogDebug(d.AtmosConfig, "Credentials found, skipping token injection\n") + u.LogDebug("Credentials found, skipping token injection\n") } } diff --git a/internal/exec/helmfile.go b/internal/exec/helmfile.go index 9c80e82cc..8991c71f4 100644 --- a/internal/exec/helmfile.go +++ b/internal/exec/helmfile.go @@ -46,7 +46,7 @@ func ExecuteHelmfile(info schema.ConfigAndStacksInfo) error { } if !info.ComponentIsEnabled { - u.LogInfo(atmosConfig, fmt.Sprintf("component '%s' is not enabled and skipped", info.ComponentFromArg)) + u.LogInfo(fmt.Sprintf("component '%s' is not enabled and skipped", info.ComponentFromArg)) return nil } @@ -83,7 +83,7 @@ func ExecuteHelmfile(info schema.ConfigAndStacksInfo) error { } // Print component variables - u.LogDebug(atmosConfig, fmt.Sprintf("\nVariables for the component '%s' in the stack '%s':", info.ComponentFromArg, info.Stack)) + u.LogDebug(fmt.Sprintf("\nVariables for the component '%s' in the stack '%s':", info.ComponentFromArg, info.Stack)) if atmosConfig.Logs.Level == u.LogLevelTrace || atmosConfig.Logs.Level == u.LogLevelDebug { err = u.PrintAsYAMLToFileDescriptor(atmosConfig, info.ComponentVarsSection) @@ -113,11 +113,11 @@ func ExecuteHelmfile(info schema.ConfigAndStacksInfo) error { varFile := constructHelmfileComponentVarfileName(info) varFilePath := constructHelmfileComponentVarfilePath(atmosConfig, info) - u.LogDebug(atmosConfig, "Writing the variables to file:") - u.LogDebug(atmosConfig, varFilePath) + u.LogDebug("Writing the variables to file:") + u.LogDebug(varFilePath) if !info.DryRun { - err = u.WriteToFileAsYAML(varFilePath, info.ComponentVarsSection, 0644) + err = u.WriteToFileAsYAML(varFilePath, info.ComponentVarsSection, 0o644) if err != nil { return err } @@ -135,12 +135,12 @@ func ExecuteHelmfile(info schema.ConfigAndStacksInfo) error { if atmosConfig.Components.Helmfile.UseEKS { // Prepare AWS profile helmAwsProfile := cfg.ReplaceContextTokens(context, atmosConfig.Components.Helmfile.HelmAwsProfilePattern) - u.LogDebug(atmosConfig, fmt.Sprintf("\nUsing AWS_PROFILE=%s\n\n", helmAwsProfile)) + u.LogDebug(fmt.Sprintf("\nUsing AWS_PROFILE=%s\n\n", helmAwsProfile)) // Download kubeconfig by running `aws eks update-kubeconfig` 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)) + u.LogDebug(fmt.Sprintf("Downloading kubeconfig from the cluster '%s' and saving it to %s\n\n", clusterName, kubeconfigPath)) err = ExecuteShellCommand( atmosConfig, @@ -170,33 +170,33 @@ func ExecuteHelmfile(info schema.ConfigAndStacksInfo) error { } // Print command info - u.LogDebug(atmosConfig, "\nCommand info:") - u.LogDebug(atmosConfig, "Helmfile binary: "+info.Command) - u.LogDebug(atmosConfig, "Helmfile command: "+info.SubCommand) + u.LogDebug("\nCommand info:") + u.LogDebug("Helmfile binary: " + info.Command) + u.LogDebug("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(atmosConfig, fmt.Sprintf("Global options: %v", info.GlobalOptions)) + u.LogDebug(fmt.Sprintf("Global options: %v", info.GlobalOptions)) - u.LogDebug(atmosConfig, fmt.Sprintf("Arguments and flags: %v", info.AdditionalArgsAndFlags)) - u.LogDebug(atmosConfig, "Component: "+info.ComponentFromArg) + u.LogDebug(fmt.Sprintf("Arguments and flags: %v", info.AdditionalArgsAndFlags)) + u.LogDebug("Component: " + info.ComponentFromArg) if len(info.BaseComponent) > 0 { - u.LogDebug(atmosConfig, "Helmfile component: "+info.BaseComponent) + u.LogDebug("Helmfile component: " + info.BaseComponent) } if info.Stack == info.StackFromArg { - u.LogDebug(atmosConfig, "Stack: "+info.StackFromArg) + u.LogDebug("Stack: " + info.StackFromArg) } else { - u.LogDebug(atmosConfig, "Stack: "+info.StackFromArg) - u.LogDebug(atmosConfig, "Stack path: "+filepath.Join(atmosConfig.BasePath, atmosConfig.Stacks.BasePath, info.Stack)) + u.LogDebug("Stack: " + info.StackFromArg) + u.LogDebug("Stack path: " + filepath.Join(atmosConfig.BasePath, atmosConfig.Stacks.BasePath, info.Stack)) } workingDir := constructHelmfileComponentWorkingDir(atmosConfig, info) - u.LogDebug(atmosConfig, fmt.Sprintf("Working dir: %s\n\n", workingDir)) + u.LogDebug(fmt.Sprintf("Working dir: %s\n\n", workingDir)) // Prepare arguments and flags allArgsAndFlags := []string{"--state-values-file", varFile} @@ -241,9 +241,9 @@ func ExecuteHelmfile(info schema.ConfigAndStacksInfo) error { envVars = append(envVars, envVarsEKS...) } - u.LogTrace(atmosConfig, "Using ENV vars:") + u.LogTrace("Using ENV vars:") for _, v := range envVars { - u.LogTrace(atmosConfig, v) + u.LogTrace(v) } err = ExecuteShellCommand( @@ -262,7 +262,7 @@ func ExecuteHelmfile(info schema.ConfigAndStacksInfo) error { // Cleanup err = os.Remove(varFilePath) if err != nil { - u.LogWarning(atmosConfig, err.Error()) + u.LogWarning(err.Error()) } return nil diff --git a/internal/exec/helmfile_generate_varfile.go b/internal/exec/helmfile_generate_varfile.go index 2f1ac4da8..0213c73b4 100644 --- a/internal/exec/helmfile_generate_varfile.go +++ b/internal/exec/helmfile_generate_varfile.go @@ -59,7 +59,7 @@ func ExecuteHelmfileGenerateVarfileCmd(cmd *cobra.Command, args []string) error } // Print the component variables - u.LogDebug(atmosConfig, fmt.Sprintf("\nVariables for the component '%s' in the stack '%s':", info.ComponentFromArg, info.Stack)) + u.LogDebug(fmt.Sprintf("\nVariables for the component '%s' in the stack '%s':", info.ComponentFromArg, info.Stack)) if atmosConfig.Logs.Level == u.LogLevelTrace || atmosConfig.Logs.Level == u.LogLevelDebug { err = u.PrintAsYAMLToFileDescriptor(atmosConfig, info.ComponentVarsSection) @@ -69,11 +69,11 @@ func ExecuteHelmfileGenerateVarfileCmd(cmd *cobra.Command, args []string) error } // Write the variables to file - u.LogDebug(atmosConfig, "Writing the variables to file:") - u.LogDebug(atmosConfig, varFilePath) + u.LogDebug("Writing the variables to file:") + u.LogDebug(varFilePath) if !info.DryRun { - err = u.WriteToFileAsYAML(varFilePath, info.ComponentVarsSection, 0644) + err = u.WriteToFileAsYAML(varFilePath, info.ComponentVarsSection, 0o644) if err != nil { return err } diff --git a/internal/exec/oci_utils.go b/internal/exec/oci_utils.go index 49b591658..dde817233 100644 --- a/internal/exec/oci_utils.go +++ b/internal/exec/oci_utils.go @@ -60,7 +60,7 @@ func processOciImage(atmosConfig schema.AtmosConfiguration, imageName string, de m, err := tarball.LoadManifest(func() (io.ReadCloser, error) { f, err := os.Open(tempTarFileName) if err != nil { - u.LogError(atmosConfig, err) + u.LogError(err) return nil, err } return f, nil diff --git a/internal/exec/shell_utils.go b/internal/exec/shell_utils.go index 119058172..689703598 100644 --- a/internal/exec/shell_utils.go +++ b/internal/exec/shell_utils.go @@ -78,24 +78,24 @@ func ExecuteShellCommand( } else if redirectStdError == "" { cmd.Stderr = os.Stderr } else { - f, err := os.OpenFile(redirectStdError, os.O_WRONLY|os.O_CREATE, 0644) + f, err := os.OpenFile(redirectStdError, os.O_WRONLY|os.O_CREATE, 0o644) if err != nil { - u.LogWarning(atmosConfig, err.Error()) + u.LogWarning(err.Error()) return err } defer func(f *os.File) { err = f.Close() if err != nil { - u.LogWarning(atmosConfig, err.Error()) + u.LogWarning(err.Error()) } }(f) cmd.Stderr = f } - u.LogDebug(atmosConfig, "\nExecuting command:") - u.LogDebug(atmosConfig, cmd.String()) + u.LogDebug("\nExecuting command:") + u.LogDebug(cmd.String()) if dryRun { return nil @@ -119,8 +119,8 @@ func ExecuteShell( } updatedEnv := append(env, fmt.Sprintf("ATMOS_SHLVL=%d", newShellLevel)) - u.LogDebug(atmosConfig, "\nExecuting command:") - u.LogDebug(atmosConfig, command) + u.LogDebug("\nExecuting command:") + u.LogDebug(command) if dryRun { return nil @@ -146,8 +146,8 @@ func ExecuteShellAndReturnOutput( } updatedEnv := append(env, fmt.Sprintf("ATMOS_SHLVL=%d", newShellLevel)) - u.LogDebug(atmosConfig, "\nExecuting command:") - u.LogDebug(atmosConfig, command) + u.LogDebug("\nExecuting command:") + u.LogDebug(command) if dryRun { return "", nil @@ -191,8 +191,8 @@ func execTerraformShellCommand( varFile string, workingDir string, workspaceName string, - componentPath string) error { - + componentPath string, +) error { atmosShellLvl := os.Getenv("ATMOS_SHLVL") atmosShellVal := 1 if atmosShellLvl != "" { @@ -214,7 +214,7 @@ func execTerraformShellCommand( } val, err := strconv.Atoi(atmosShellLvl) if err != nil { - u.LogWarning(atmosConfig, fmt.Sprintf("Failed to parse ATMOS_SHLVL: %v", err)) + u.LogWarning(fmt.Sprintf("Failed to parse ATMOS_SHLVL: %v", err)) return } // Prevent negative values @@ -223,7 +223,7 @@ func execTerraformShellCommand( newVal = 0 } if err := os.Setenv("ATMOS_SHLVL", fmt.Sprintf("%d", newVal)); err != nil { - u.LogWarning(atmosConfig, fmt.Sprintf("Failed to update ATMOS_SHLVL: %v", err)) + u.LogWarning(fmt.Sprintf("Failed to update ATMOS_SHLVL: %v", err)) } }() @@ -261,12 +261,12 @@ func execTerraformShellCommand( } } - 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") + u.LogDebug("\nStarting a new interactive shell where you can execute all native Terraform commands (type 'exit' to go back)") + u.LogDebug(fmt.Sprintf("Component: %s\n", component)) + u.LogDebug(fmt.Sprintf("Stack: %s\n", stack)) + u.LogDebug(fmt.Sprintf("Working directory: %s\n", workingDir)) + u.LogDebug(fmt.Sprintf("Terraform workspace: %s\n", workspaceName)) + u.LogDebug("\nSetting the ENV vars in the shell:\n") // Merge env vars, ensuring componentEnvList takes precedence mergedEnv := mergeEnvVars(atmosConfig, componentEnvList) @@ -314,7 +314,7 @@ func execTerraformShellCommand( } } - u.LogDebug(atmosConfig, fmt.Sprintf("Starting process: %s\n", shellCommand)) + u.LogDebug(fmt.Sprintf("Starting process: %s\n", shellCommand)) args := strings.Fields(shellCommand) @@ -329,7 +329,7 @@ func execTerraformShellCommand( return err } - u.LogDebug(atmosConfig, fmt.Sprintf("Exited shell: %s\n", state.String())) + u.LogDebug(fmt.Sprintf("Exited shell: %s\n", state.String())) return nil } @@ -346,7 +346,7 @@ func mergeEnvVars(atmosConfig schema.AtmosConfiguration, componentEnvList []stri for _, env := range os.Environ() { if parts := strings.SplitN(env, "=", 2); len(parts) == 2 { if strings.HasPrefix(parts[0], "TF_") { - u.LogWarning(atmosConfig, fmt.Sprintf("detected '%s' set in the environment; this may interfere with Atmos's control of Terraform.", parts[0])) + u.LogWarning(fmt.Sprintf("detected '%s' set in the environment; this may interfere with Atmos's control of Terraform.", parts[0])) } envMap[parts[0]] = parts[1] } @@ -375,7 +375,7 @@ func mergeEnvVars(atmosConfig schema.AtmosConfiguration, componentEnvList []stri // Convert back to slice merged := make([]string, 0, len(envMap)) for k, v := range envMap { - u.LogDebug(atmosConfig, fmt.Sprintf("%s=%s", k, v)) + u.LogDebug(fmt.Sprintf("%s=%s", k, v)) merged = append(merged, k+"="+v) } return merged diff --git a/internal/exec/tar_utils.go b/internal/exec/tar_utils.go index bcd1f1392..7a171f2d2 100644 --- a/internal/exec/tar_utils.go +++ b/internal/exec/tar_utils.go @@ -42,7 +42,7 @@ func extractTarball(atmosConfig schema.AtmosConfiguration, sourceFile, extractPa } if strings.Contains(header.Name, "..") { - u.LogTrace(atmosConfig, fmt.Sprintf("the header '%s' in the tarball '%s' contains '..', "+ + u.LogTrace(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(atmosConfig schema.AtmosConfiguration, sourceFile, extractPa } default: - u.LogTrace(atmosConfig, fmt.Sprintf("the header '%s' in the tarball '%s' has unsupported header type '%v'. "+ + u.LogTrace(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_component.go b/internal/exec/template_funcs_component.go index 1fa4c9269..2245ecdb4 100644 --- a/internal/exec/template_funcs_component.go +++ b/internal/exec/template_funcs_component.go @@ -10,12 +10,10 @@ import ( u "github.com/cloudposse/atmos/pkg/utils" ) -var ( - componentFuncSyncMap = sync.Map{} -) +var componentFuncSyncMap = sync.Map{} 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)) + u.LogTrace(fmt.Sprintf("Executing template function 'atmos.Component(%s, %s)'", component, stack)) stackSlug := fmt.Sprintf("%s-%s", stack, component) @@ -23,15 +21,15 @@ func componentFunc(atmosConfig schema.AtmosConfiguration, component string, stac existingSections, found := componentFuncSyncMap.Load(stackSlug) if found && existingSections != nil { 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)) + u.LogTrace(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(atmosConfig, "'outputs' section:") + u.LogTrace("'outputs' section:") y, err2 := u.ConvertToYAML(outputsSection) if err2 != nil { - u.LogError(atmosConfig, err2) + u.LogError(err2) } else { - u.LogTrace(atmosConfig, y) + u.LogTrace(y) } } } @@ -73,12 +71,12 @@ func componentFunc(atmosConfig schema.AtmosConfiguration, component string, stac componentFuncSyncMap.Store(stackSlug, sections) if atmosConfig.Logs.Level == u.LogLevelTrace { - u.LogTrace(atmosConfig, fmt.Sprintf("Executed template function 'atmos.Component(%s, %s)'\n\n'outputs' section:", component, stack)) + u.LogTrace(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(atmosConfig, err2) + u.LogError(err2) } else { - u.LogTrace(atmosConfig, y) + u.LogTrace(y) } } diff --git a/internal/exec/template_funcs_gomplate_datasource.go b/internal/exec/template_funcs_gomplate_datasource.go index 318de5400..14ac8ebd4 100644 --- a/internal/exec/template_funcs_gomplate_datasource.go +++ b/internal/exec/template_funcs_gomplate_datasource.go @@ -2,19 +2,18 @@ package exec import ( "fmt" - u "github.com/cloudposse/atmos/pkg/utils" "sync" + u "github.com/cloudposse/atmos/pkg/utils" + "github.com/cloudposse/atmos/pkg/schema" "github.com/hairyhenderson/gomplate/v3/data" ) -var ( - gomplateDatasourceFuncSyncMap = sync.Map{} -) +var gomplateDatasourceFuncSyncMap = sync.Map{} 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)) + u.LogTrace(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 +29,7 @@ func gomplateDatasourceFunc(atmosConfig schema.AtmosConfiguration, alias string, // Cache the result gomplateDatasourceFuncSyncMap.Store(alias, result) - u.LogTrace(atmosConfig, fmt.Sprintf("atmos.GomplateDatasource(): processed datasource alias '%s'.\nResult: '%v'", alias, result)) + u.LogTrace(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 2ecc969d4..09b5a3fdf 100644 --- a/internal/exec/template_utils.go +++ b/internal/exec/template_utils.go @@ -70,11 +70,11 @@ func ProcessTmplWithDatasources( ignoreMissingTemplateValues bool, ) (string, error) { if !atmosConfig.Templates.Settings.Enabled { - u.LogTrace(atmosConfig, fmt.Sprintf("ProcessTmplWithDatasources: not processing template '%s' since templating is disabled in 'atmos.yaml'", tmplName)) + u.LogTrace(fmt.Sprintf("ProcessTmplWithDatasources: not processing template '%s' since templating is disabled in 'atmos.yaml'", tmplName)) return tmplValue, nil } - u.LogTrace(atmosConfig, fmt.Sprintf("ProcessTmplWithDatasources(): processing template '%s'", tmplName)) + u.LogTrace(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 @@ -109,7 +109,7 @@ func ProcessTmplWithDatasources( result := tmplValue for i := 0; i < evaluations; i++ { - u.LogTrace(atmosConfig, fmt.Sprintf("ProcessTmplWithDatasources(): template '%s' - evaluation %d", tmplName, i+1)) + u.LogTrace(fmt.Sprintf("ProcessTmplWithDatasources(): template '%s' - evaluation %d", tmplName, i+1)) d := data.Data{} @@ -229,7 +229,7 @@ func ProcessTmplWithDatasources( } } - u.LogTrace(atmosConfig, fmt.Sprintf("ProcessTmplWithDatasources(): processed template '%s'", tmplName)) + u.LogTrace(fmt.Sprintf("ProcessTmplWithDatasources(): processed template '%s'", tmplName)) return result, nil } diff --git a/internal/exec/terraform.go b/internal/exec/terraform.go index c1acc4a95..deceff0c5 100644 --- a/internal/exec/terraform.go +++ b/internal/exec/terraform.go @@ -52,8 +52,8 @@ func generateBackendConfig(atmosConfig *schema.AtmosConfiguration, info *schema. if atmosConfig.Components.Terraform.AutoGenerateBackendFile { backendFileName := filepath.Join(workingDir, "backend.tf.json") - u.LogDebug(*atmosConfig, "\nWriting the backend config to file:") - u.LogDebug(*atmosConfig, backendFileName) + u.LogDebug("\nWriting the backend config to file:") + u.LogDebug(backendFileName) if !info.DryRun { componentBackendConfig, err := generateComponentBackendConfig(info.ComponentBackendType, info.ComponentBackendSection, info.TerraformWorkspace) @@ -61,7 +61,7 @@ func generateBackendConfig(atmosConfig *schema.AtmosConfiguration, info *schema. return err } - err = u.WriteToFileAsJSON(backendFileName, componentBackendConfig, 0644) + err = u.WriteToFileAsJSON(backendFileName, componentBackendConfig, 0o644) if err != nil { return err } @@ -76,12 +76,12 @@ func generateProviderOverrides(atmosConfig *schema.AtmosConfiguration, info *sch if len(info.ComponentProvidersSection) > 0 { providerOverrideFileName := filepath.Join(workingDir, "providers_override.tf.json") - u.LogDebug(*atmosConfig, "\nWriting the provider overrides to file:") - u.LogDebug(*atmosConfig, providerOverrideFileName) + u.LogDebug("\nWriting the provider overrides to file:") + u.LogDebug(providerOverrideFileName) if !info.DryRun { - var providerOverrides = generateComponentProviderOverrides(info.ComponentProvidersSection) - err := u.WriteToFileAsJSON(providerOverrideFileName, providerOverrides, 0644) + providerOverrides := generateComponentProviderOverrides(info.ComponentProvidersSection) + err := u.WriteToFileAsJSON(providerOverrideFileName, providerOverrides, 0o644) return err } } @@ -125,7 +125,7 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { } if !info.ComponentIsEnabled && info.SubCommand != "clean" { - u.LogInfo(atmosConfig, fmt.Sprintf("component '%s' is not enabled and skipped", info.ComponentFromArg)) + u.LogInfo(fmt.Sprintf("component '%s' is not enabled and skipped", info.ComponentFromArg)) return nil } @@ -164,7 +164,7 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { if info.SubCommand == "clean" { err := handleCleanSubCommand(info, componentPath, atmosConfig) if err != nil { - u.LogTrace(atmosConfig, fmt.Errorf("error cleaning the terraform component: %v", err).Error()) + u.LogDebug(fmt.Errorf("error cleaning the terraform component: %v", err).Error()) return err } return nil @@ -176,7 +176,7 @@ 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(atmosConfig, fmt.Sprintf("\nVariables for the component '%s' in the stack '%s':", info.ComponentFromArg, info.Stack)) + u.LogDebug(fmt.Sprintf("\nVariables for the component '%s' in the stack '%s':", info.ComponentFromArg, info.Stack)) if atmosConfig.Logs.Level == u.LogLevelTrace || atmosConfig.Logs.Level == u.LogLevelDebug { err = u.PrintAsYAMLToFileDescriptor(atmosConfig, info.ComponentVarsSection) if err != nil { @@ -204,11 +204,11 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { varFilePath = constructTerraformComponentVarfilePath(atmosConfig, info) } - u.LogDebug(atmosConfig, "Writing the variables to file:") - u.LogDebug(atmosConfig, varFilePath) + u.LogDebug("Writing the variables to file:") + u.LogDebug(varFilePath) if !info.DryRun { - err = u.WriteToFileAsJSON(varFilePath, info.ComponentVarsSection, 0644) + err = u.WriteToFileAsJSON(varFilePath, info.ComponentVarsSection, 0o644) if err != nil { return err } @@ -225,7 +225,7 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { - Default values in the configuration file: these have the lowest priority */ if cliVars, ok := info.ComponentSection[cfg.TerraformCliVarsSectionName].(map[string]any); ok && len(cliVars) > 0 { - u.LogDebug(atmosConfig, "\nCLI variables (will override the variables defined in the stack manifests):") + u.LogDebug("\nCLI variables (will override the variables defined in the stack manifests):") if atmosConfig.Logs.Level == u.LogLevelTrace || atmosConfig.Logs.Level == u.LogLevelDebug { err = u.PrintAsYAMLToFileDescriptor(atmosConfig, cliVars) if err != nil { @@ -275,7 +275,7 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { for _, envVar := range os.Environ() { if strings.HasPrefix(envVar, "TF_") { varName := strings.SplitN(envVar, "=", 2)[0] - u.LogWarning(atmosConfig, fmt.Sprintf("detected '%s' set in the environment; this may interfere with Atmos's control of Terraform.", varName)) + u.LogWarning(fmt.Sprintf("detected '%s' set in the environment; this may interfere with Atmos's control of Terraform.", varName)) } } @@ -295,9 +295,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(atmosConfig, "\nUsing ENV vars:") + u.LogDebug("\nUsing ENV vars:") for _, v := range info.ComponentEnvList { - u.LogDebug(atmosConfig, v) + u.LogDebug(v) } } @@ -310,7 +310,7 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { } if info.SkipInit { - u.LogDebug(atmosConfig, "Skipping over 'terraform init' due to '--skip-init' flag being passed") + u.LogDebug("Skipping over 'terraform init' due to '--skip-init' flag being passed") runTerraformInit = false } @@ -353,34 +353,34 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error { } // Print command info - u.LogDebug(atmosConfig, "\nCommand info:") - u.LogDebug(atmosConfig, "Terraform binary: "+info.Command) + u.LogDebug("\nCommand info:") + u.LogDebug("Terraform binary: " + info.Command) if info.SubCommand2 == "" { - u.LogDebug(atmosConfig, fmt.Sprintf("Terraform command: %s", info.SubCommand)) + u.LogDebug(fmt.Sprintf("Terraform command: %s", info.SubCommand)) } else { - u.LogDebug(atmosConfig, fmt.Sprintf("Terraform command: %s %s", info.SubCommand, info.SubCommand2)) + u.LogDebug(fmt.Sprintf("Terraform command: %s %s", info.SubCommand, info.SubCommand2)) } - u.LogDebug(atmosConfig, fmt.Sprintf("Arguments and flags: %v", info.AdditionalArgsAndFlags)) - u.LogDebug(atmosConfig, "Component: "+info.ComponentFromArg) + u.LogDebug(fmt.Sprintf("Arguments and flags: %v", info.AdditionalArgsAndFlags)) + u.LogDebug("Component: " + info.ComponentFromArg) if len(info.BaseComponentPath) > 0 { - u.LogDebug(atmosConfig, "Terraform component: "+info.BaseComponentPath) + u.LogDebug("Terraform component: " + info.BaseComponentPath) } if len(info.ComponentInheritanceChain) > 0 { - u.LogDebug(atmosConfig, "Inheritance: "+info.ComponentFromArg+" -> "+strings.Join(info.ComponentInheritanceChain, " -> ")) + u.LogDebug("Inheritance: " + info.ComponentFromArg + " -> " + strings.Join(info.ComponentInheritanceChain, " -> ")) } if info.Stack == info.StackFromArg { - u.LogDebug(atmosConfig, "Stack: "+info.StackFromArg) + u.LogDebug("Stack: " + info.StackFromArg) } else { - u.LogDebug(atmosConfig, "Stack: "+info.StackFromArg) - u.LogDebug(atmosConfig, "Stack path: "+filepath.Join(atmosConfig.BasePath, atmosConfig.Stacks.BasePath, info.Stack)) + u.LogDebug("Stack: " + info.StackFromArg) + u.LogDebug("Stack path: " + filepath.Join(atmosConfig.BasePath, atmosConfig.Stacks.BasePath, info.Stack)) } - u.LogDebug(atmosConfig, fmt.Sprintf("Working dir: %s", workingDir)) + u.LogDebug(fmt.Sprintf("Working dir: %s", workingDir)) allArgsAndFlags := strings.Fields(info.SubCommand) diff --git a/internal/exec/terraform_clean.go b/internal/exec/terraform_clean.go index 3544eae72..aa381960f 100644 --- a/internal/exec/terraform_clean.go +++ b/internal/exec/terraform_clean.go @@ -51,7 +51,7 @@ func findFoldersNamesWithPrefix(root, prefix string, atmosConfig schema.AtmosCon level2Path := filepath.Join(root, dir.Name()) level2Dirs, err := os.ReadDir(level2Path) if err != nil { - u.LogWarning(atmosConfig, fmt.Sprintf("Error reading subdirectory %s: %v", level2Path, err)) + u.LogWarning(fmt.Sprintf("Error reading subdirectory %s: %v", level2Path, err)) continue } @@ -201,9 +201,7 @@ func getStackTerraformStateFolder(componentPath string, stack string, atmosConfi if directories[i].Files != nil { for j := range directories[i].Files { directories[i].Files[j].Name = folderName + "/" + directories[i].Files[j].Name - } - } } stackTfStateFolders = append(stackTfStateFolders, directories...) @@ -230,6 +228,7 @@ func getRelativePath(basePath, componentPath string) (string, error) { return filepath.Base(absBasePath) + "/" + relPath, nil } + func confirmDeleteTerraformLocal(message string) (confirm bool, err error) { confirm = false t := huh.ThemeCharm() @@ -287,7 +286,7 @@ func confirmDeletion(atmosConfig schema.AtmosConfiguration) (bool, error) { return false, err } if !confirm { - u.LogWarning(atmosConfig, "Mission aborted.") + u.LogWarning("Mission aborted.") return false, nil } return true, nil @@ -312,7 +311,7 @@ func deleteFolders(folders []Directory, relativePath string, atmosConfig schema. } if len(errors) > 0 { for _, err := range errors { - u.LogWarning(atmosConfig, err.Error()) + u.LogWarning(err.Error()) } } // check if the folder is empty by using the os.ReadDir function @@ -320,33 +319,31 @@ func deleteFolders(folders []Directory, relativePath string, atmosConfig schema. entries, err := os.ReadDir(folder.FullPath) if err == nil && len(entries) == 0 { if err := os.Remove(folder.FullPath); err != nil { - u.LogWarning(atmosConfig, fmt.Sprintf("Error removing directory %s: %v", folder.FullPath, err)) + u.LogWarning(fmt.Sprintf("Error removing directory %s: %v", folder.FullPath, err)) } } } - } // handleTFDataDir handles the deletion of the TF_DATA_DIR if specified. 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(atmosConfig, err.Error()) + u.LogWarning(err.Error()) return } if _, err := os.Stat(filepath.Join(componentPath, tfDataDir)); os.IsNotExist(err) { - u.LogWarning(atmosConfig, fmt.Sprintf("TF_DATA_DIR '%s' does not exist", tfDataDir)) + u.LogWarning(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(atmosConfig, err.Error()) + u.LogWarning(err.Error()) } - } + func initializeFilesToClear(info schema.ConfigAndStacksInfo, atmosConfig schema.AtmosConfiguration) []string { if info.ComponentFromArg == "" { return []string{".terraform", ".terraform.lock.hcl", "*.tfvar.json", "terraform.tfstate.d"} @@ -365,6 +362,7 @@ func initializeFilesToClear(info schema.ConfigAndStacksInfo, atmosConfig schema. return files } + func IsValidDataDir(tfDataDir string) error { if tfDataDir == "" { return fmt.Errorf("ENV TF_DATA_DIR is empty") @@ -410,7 +408,7 @@ func handleCleanSubCommand(info schema.ConfigAndStacksInfo, componentPath string filesToClear := initializeFilesToClear(info, atmosConfig) folders, err := CollectDirectoryObjects(cleanPath, filesToClear) if err != nil { - u.LogTrace(atmosConfig, fmt.Errorf("error collecting folders and files: %v", err).Error()) + u.LogTrace(fmt.Errorf("error collecting folders and files: %v", err).Error()) return err } @@ -418,7 +416,7 @@ func handleCleanSubCommand(info schema.ConfigAndStacksInfo, componentPath string stackFolders, err := getStackTerraformStateFolder(cleanPath, info.Stack, atmosConfig) if err != nil { errMsg := fmt.Errorf("error getting stack terraform state folders: %v", err) - u.LogTrace(atmosConfig, errMsg.Error()) + u.LogTrace(errMsg.Error()) } if stackFolders != nil { folders = append(folders, stackFolders...) @@ -429,11 +427,11 @@ func handleCleanSubCommand(info schema.ConfigAndStacksInfo, componentPath string var tfDataDirFolders []Directory if tfDataDir != "" { if err := IsValidDataDir(tfDataDir); err != nil { - u.LogTrace(atmosConfig, err.Error()) + u.LogTrace(err.Error()) } else { tfDataDirFolders, err = CollectDirectoryObjects(cleanPath, []string{tfDataDir}) if err != nil { - u.LogTrace(atmosConfig, fmt.Errorf("error collecting folder of ENV TF_DATA_DIR: %v", err).Error()) + u.LogTrace(fmt.Errorf("error collecting folder of ENV TF_DATA_DIR: %v", err).Error()) } } } diff --git a/internal/exec/terraform_generate_backend.go b/internal/exec/terraform_generate_backend.go index 632b8e508..f185205ef 100644 --- a/internal/exec/terraform_generate_backend.go +++ b/internal/exec/terraform_generate_backend.go @@ -58,7 +58,7 @@ func ExecuteTerraformGenerateBackendCmd(cmd *cobra.Command, args []string) error return err } - u.LogDebug(atmosConfig, "Component backend config:\n\n") + u.LogDebug("Component backend config:\n\n") if atmosConfig.Logs.Level == u.LogLevelTrace || atmosConfig.Logs.Level == u.LogLevelDebug { err = u.PrintAsJSONToFileDescriptor(atmosConfig, componentBackendConfig) @@ -75,7 +75,7 @@ func ExecuteTerraformGenerateBackendCmd(cmd *cobra.Command, args []string) error } // Write backend config to file - var backendFilePath = filepath.Join( + backendFilePath := filepath.Join( atmosConfig.BasePath, atmosConfig.Components.Terraform.BasePath, info.ComponentFolderPrefix, @@ -83,11 +83,11 @@ func ExecuteTerraformGenerateBackendCmd(cmd *cobra.Command, args []string) error "backend.tf.json", ) - u.LogDebug(atmosConfig, "\nWriting the backend config to file:") - u.LogDebug(atmosConfig, backendFilePath) + u.LogDebug("\nWriting the backend config to file:") + u.LogDebug(backendFilePath) if !info.DryRun { - err = u.WriteToFileAsJSON(backendFilePath, componentBackendConfig, 0644) + err = u.WriteToFileAsJSON(backendFilePath, componentBackendConfig, 0o644) if err != nil { return err } diff --git a/internal/exec/terraform_generate_backends.go b/internal/exec/terraform_generate_backends.go index 99099edb1..3ce0b4350 100644 --- a/internal/exec/terraform_generate_backends.go +++ b/internal/exec/terraform_generate_backends.go @@ -257,7 +257,7 @@ func ExecuteTerraformGenerateBackends( err = errors.Join(err, errors.New(errorMessage)) } } - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } componentSectionFinal, err := ProcessCustomYamlTags(atmosConfig, componentSectionConverted, stackName) @@ -327,7 +327,7 @@ func ExecuteTerraformGenerateBackends( } // Write the backend config to the file - u.LogDebug(atmosConfig, fmt.Sprintf("Writing backend config for the component '%s' to file '%s'", terraformComponent, backendFilePath)) + u.LogDebug(fmt.Sprintf("Writing backend config for the component '%s' to file '%s'", terraformComponent, backendFilePath)) if format == "json" { componentBackendConfig, err := generateComponentBackendConfig(backendTypeSection, backendSection, "") @@ -335,7 +335,7 @@ func ExecuteTerraformGenerateBackends( return err } - err = u.WriteToFileAsJSON(backendFileAbsolutePath, componentBackendConfig, 0644) + err = u.WriteToFileAsJSON(backendFileAbsolutePath, componentBackendConfig, 0o644) if err != nil { return err } @@ -345,7 +345,7 @@ func ExecuteTerraformGenerateBackends( return err } } else if format == "backend-config" { - err = u.WriteToFileAsHcl(atmosConfig, backendFileAbsolutePath, backendSection, 0644) + err = u.WriteToFileAsHcl(atmosConfig, backendFileAbsolutePath, backendSection, 0o644) if err != nil { return err } diff --git a/internal/exec/terraform_generate_varfile.go b/internal/exec/terraform_generate_varfile.go index 6bc8263f6..b94a708a3 100644 --- a/internal/exec/terraform_generate_varfile.go +++ b/internal/exec/terraform_generate_varfile.go @@ -59,7 +59,7 @@ func ExecuteTerraformGenerateVarfileCmd(cmd *cobra.Command, args []string) error } // Print the component variables - u.LogDebug(atmosConfig, fmt.Sprintf("\nVariables for the component '%s' in the stack '%s':", info.ComponentFromArg, info.Stack)) + u.LogDebug(fmt.Sprintf("\nVariables for the component '%s' in the stack '%s':", info.ComponentFromArg, info.Stack)) if atmosConfig.Logs.Level == u.LogLevelTrace || atmosConfig.Logs.Level == u.LogLevelDebug { err = u.PrintAsYAMLToFileDescriptor(atmosConfig, info.ComponentVarsSection) @@ -69,11 +69,11 @@ func ExecuteTerraformGenerateVarfileCmd(cmd *cobra.Command, args []string) error } // Write the variables to file - u.LogDebug(atmosConfig, "Writing the variables to file:") - u.LogDebug(atmosConfig, varFilePath) + u.LogDebug("Writing the variables to file:") + u.LogDebug(varFilePath) if !info.DryRun { - err = u.WriteToFileAsJSON(varFilePath, info.ComponentVarsSection, 0644) + err = u.WriteToFileAsJSON(varFilePath, info.ComponentVarsSection, 0o644) if err != nil { return err } diff --git a/internal/exec/terraform_generate_varfiles.go b/internal/exec/terraform_generate_varfiles.go index 04ef9466f..55e9452d1 100644 --- a/internal/exec/terraform_generate_varfiles.go +++ b/internal/exec/terraform_generate_varfiles.go @@ -266,7 +266,7 @@ func ExecuteTerraformGenerateVarfiles( err = errors.Join(err, errors.New(errorMessage)) } } - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } componentSectionFinal, err := ProcessCustomYamlTags(atmosConfig, componentSectionConverted, stackName) @@ -305,17 +305,17 @@ func ExecuteTerraformGenerateVarfiles( // Write the varfile if format == "yaml" { - err = u.WriteToFileAsYAML(fileAbsolutePath, varsSection, 0644) + err = u.WriteToFileAsYAML(fileAbsolutePath, varsSection, 0o644) if err != nil { return err } } else if format == "json" { - err = u.WriteToFileAsJSON(fileAbsolutePath, varsSection, 0644) + err = u.WriteToFileAsJSON(fileAbsolutePath, varsSection, 0o644) if err != nil { return err } } else if format == "hcl" { - err = u.WriteToFileAsHcl(atmosConfig, fileAbsolutePath, varsSection, 0644) + err = u.WriteToFileAsHcl(atmosConfig, fileAbsolutePath, varsSection, 0o644) 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(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)) + u.LogDebug(fmt.Sprintf("varfile: %s", fileName)) + u.LogDebug(fmt.Sprintf("terraform component: %s", terraformComponent)) + u.LogDebug(fmt.Sprintf("atmos component: %s", componentName)) + u.LogDebug(fmt.Sprintf("atmos stack: %s", stackName)) + u.LogDebug(fmt.Sprintf("stack config file: %s", stackFileName)) } } } diff --git a/internal/exec/terraform_outputs.go b/internal/exec/terraform_outputs.go index 2010d58f8..00a7db892 100644 --- a/internal/exec/terraform_outputs.go +++ b/internal/exec/terraform_outputs.go @@ -19,9 +19,7 @@ import ( u "github.com/cloudposse/atmos/pkg/utils" ) -var ( - terraformOutputsCache = sync.Map{} -) +var terraformOutputsCache = sync.Map{} func execTerraformOutput(atmosConfig *schema.AtmosConfiguration, component string, @@ -80,8 +78,8 @@ func execTerraformOutput(atmosConfig *schema.AtmosConfiguration, if atmosConfig.Components.Terraform.AutoGenerateBackendFile { backendFileName := filepath.Join(componentPath, "backend.tf.json") - u.LogTrace(*atmosConfig, "\nWriting the backend config to file:") - u.LogTrace(*atmosConfig, backendFileName) + u.LogDebug("\nWriting the backend config to file:") + u.LogDebug(backendFileName) backendTypeSection, ok := sections["backend_type"].(string) if !ok { @@ -98,13 +96,13 @@ func execTerraformOutput(atmosConfig *schema.AtmosConfiguration, return nil, err } - err = u.WriteToFileAsJSON(backendFileName, componentBackendConfig, 0644) + err = u.WriteToFileAsJSON(backendFileName, componentBackendConfig, 0o644) if err != nil { return nil, err } - u.LogTrace(*atmosConfig, "\nWrote the backend config to file:") - u.LogTrace(*atmosConfig, backendFileName) + u.LogDebug("\nWrote the backend config to file:") + u.LogDebug(backendFileName) } // Generate `providers_override.tf.json` file if the `providers` section is configured @@ -113,17 +111,17 @@ func execTerraformOutput(atmosConfig *schema.AtmosConfiguration, if ok && len(providersSection) > 0 { providerOverrideFileName := filepath.Join(componentPath, "providers_override.tf.json") - u.LogTrace(*atmosConfig, "\nWriting the provider overrides to file:") - u.LogTrace(*atmosConfig, providerOverrideFileName) + u.LogDebug("\nWriting the provider overrides to file:") + u.LogDebug(providerOverrideFileName) - var providerOverrides = generateComponentProviderOverrides(providersSection) - err = u.WriteToFileAsJSON(providerOverrideFileName, providerOverrides, 0644) + providerOverrides := generateComponentProviderOverrides(providersSection) + err = u.WriteToFileAsJSON(providerOverrideFileName, providerOverrides, 0o644) if err != nil { return nil, err } - u.LogTrace(*atmosConfig, "\nWrote the provider overrides to file:") - u.LogTrace(*atmosConfig, providerOverrideFileName) + u.LogDebug("\nWrote the provider overrides to file:") + u.LogDebug(providerOverrideFileName) } // Initialize Terraform/OpenTofu @@ -139,7 +137,7 @@ func execTerraformOutput(atmosConfig *schema.AtmosConfiguration, // Before executing `terraform init`, delete the `.terraform/environment` file from the component directory cleanTerraformWorkspace(*atmosConfig, componentPath) - u.LogTrace(*atmosConfig, fmt.Sprintf("\nExecuting 'terraform init %s -s %s'", component, stack)) + u.LogDebug(fmt.Sprintf("\nExecuting 'terraform init %s -s %s'", component, stack)) var initOptions []tfexec.InitOption initOptions = append(initOptions, tfexec.Upgrade(false)) @@ -151,50 +149,50 @@ func execTerraformOutput(atmosConfig *schema.AtmosConfiguration, if err != nil { return nil, err } - u.LogTrace(*atmosConfig, fmt.Sprintf("\nExecuted 'terraform init %s -s %s'", component, stack)) + u.LogDebug(fmt.Sprintf("\nExecuted 'terraform init %s -s %s'", component, stack)) // Terraform workspace - u.LogTrace(*atmosConfig, fmt.Sprintf("\nExecuting 'terraform workspace new %s' for component '%s' in stack '%s'", terraformWorkspace, component, stack)) + u.LogDebug(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(*atmosConfig, fmt.Sprintf("\nWorkspace exists. Executing 'terraform workspace select %s' for component '%s' in stack '%s'", terraformWorkspace, component, stack)) + u.LogDebug(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(*atmosConfig, fmt.Sprintf("\nExecuted 'terraform workspace select %s' for component '%s' in stack '%s'", terraformWorkspace, component, stack)) + u.LogDebug(fmt.Sprintf("\nExecuted 'terraform workspace select %s' for component '%s' in stack '%s'", terraformWorkspace, component, stack)) } else { - u.LogTrace(*atmosConfig, fmt.Sprintf("\nExecuted 'terraform workspace new %s' for component '%s' in stack '%s'", terraformWorkspace, component, stack)) + u.LogDebug(fmt.Sprintf("\nExecuted 'terraform workspace new %s' for component '%s' in stack '%s'", terraformWorkspace, component, stack)) } // Terraform output - u.LogTrace(*atmosConfig, fmt.Sprintf("\nExecuting 'terraform output %s -s %s'", component, stack)) + u.LogDebug(fmt.Sprintf("\nExecuting 'terraform output %s -s %s'", component, stack)) outputMeta, err := tf.Output(ctx) if err != nil { return nil, err } - u.LogTrace(*atmosConfig, fmt.Sprintf("\nExecuted 'terraform output %s -s %s'", component, stack)) + u.LogDebug(fmt.Sprintf("\nExecuted 'terraform output %s -s %s'", component, stack)) if atmosConfig.Logs.Level == u.LogLevelTrace { y, err2 := u.ConvertToYAML(outputMeta) if err2 != nil { - u.LogError(*atmosConfig, err2) + u.LogError(err2) } else { - u.LogTrace(*atmosConfig, fmt.Sprintf("\nResult of 'terraform output %s -s %s' before processing it:\n%s\n", component, stack, y)) + u.LogDebug(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(*atmosConfig, fmt.Sprintf("Converting the variable '%s' with the value\n%s\nfrom JSON to 'Go' data type\n", k, s)) + u.LogDebug(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(*atmosConfig, fmt.Errorf("failed to convert output '%s': %w", k, err2)) + u.LogError(fmt.Errorf("failed to convert output '%s': %w", k, err2)) return k, nil } else { - 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)) + u.LogDebug(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 @@ -204,7 +202,7 @@ func execTerraformOutput(atmosConfig *schema.AtmosConfiguration, if componentAbstract { componentStatus = "abstract" } - u.LogTrace(*atmosConfig, fmt.Sprintf("\nNot executing 'terraform output %s -s %s' because the component is %s", component, stack, componentStatus)) + u.LogDebug(fmt.Sprintf("\nNot executing 'terraform output %s -s %s' because the component is %s", component, stack, componentStatus)) } return outputProcessed, nil @@ -224,7 +222,7 @@ func GetTerraformOutput( if !skipCache { cachedOutputs, found := terraformOutputsCache.Load(stackSlug) if found && cachedOutputs != nil { - u.LogTrace(*atmosConfig, fmt.Sprintf("Found the result of the Atmos YAML function '!terraform.output %s %s %s' in the cache", component, stack, output)) + u.LogDebug(fmt.Sprintf("Found the result of the Atmos YAML function '!terraform.output %s %s %s' in the cache", component, stack, output)) return getTerraformOutputVariable(atmosConfig, component, stack, cachedOutputs.(map[string]any), output) } } @@ -237,7 +235,7 @@ func GetTerraformOutput( if !CheckTTYSupport() { // set tea.WithInput(nil) workaround tea program not run on not TTY mod issue opts = []tea.ProgramOption{tea.WithoutRenderer(), tea.WithInput(nil)} - u.LogTrace(*atmosConfig, "No TTY detected. Falling back to basic output. This can happen when no terminal is attached or when commands are pipelined.") + u.LogTrace("No TTY detected. Falling back to basic output. This can happen when no terminal is attached or when commands are pipelined.") fmt.Println(message) } @@ -251,7 +249,7 @@ func GetTerraformOutput( if _, err := p.Run(); err != nil { // If there's any error running the spinner, just print the message fmt.Println(message) - u.LogError(*atmosConfig, fmt.Errorf("failed to run spinner: %w", err)) + u.LogError(fmt.Errorf("failed to run spinner: %w", err)) } close(spinnerDone) }() @@ -261,7 +259,7 @@ func GetTerraformOutput( p.Quit() <-spinnerDone fmt.Printf("\r✗ %s\n", message) - u.LogErrorAndExit(*atmosConfig, err) + u.LogErrorAndExit(err) } // Check if the component in the stack is configured with the 'static' remote state backend, in which case get the @@ -271,7 +269,7 @@ func GetTerraformOutput( p.Quit() <-spinnerDone fmt.Printf("\r✗ %s\n", message) - u.LogErrorAndExit(*atmosConfig, err) + u.LogErrorAndExit(err) } var result any @@ -286,7 +284,7 @@ func GetTerraformOutput( p.Quit() <-spinnerDone fmt.Printf("\r✗ %s\n", message) - u.LogErrorAndExit(*atmosConfig, err) + u.LogErrorAndExit(err) } // Cache the result @@ -315,9 +313,8 @@ func getTerraformOutputVariable( } res, err := u.EvaluateYqExpression(atmosConfig, outputs, val) - if err != nil { - u.LogErrorAndExit(*atmosConfig, fmt.Errorf("error evaluating terrform output '%s' for the component '%s' in the stack '%s':\n%v", + u.LogErrorAndExit(fmt.Errorf("error evaluating terrform output '%s' for the component '%s' in the stack '%s':\n%v", output, component, stack, @@ -341,9 +338,8 @@ func getStaticRemoteStateOutput( } res, err := u.EvaluateYqExpression(atmosConfig, remoteStateSection, val) - if err != nil { - u.LogErrorAndExit(*atmosConfig, fmt.Errorf("error evaluating the 'static' remote state backend output '%s' for the component '%s' in the stack '%s':\n%v", + u.LogErrorAndExit(fmt.Errorf("error evaluating the 'static' remote state backend output '%s' for the component '%s' in the stack '%s':\n%v", output, component, stack, diff --git a/internal/exec/terraform_utils.go b/internal/exec/terraform_utils.go index 979e826b5..466a88f04 100644 --- a/internal/exec/terraform_utils.go +++ b/internal/exec/terraform_utils.go @@ -26,6 +26,6 @@ func checkTerraformConfig(atmosConfig schema.AtmosConfiguration) error { // previously used workspace. This happens when different backends are used for the same component. func cleanTerraformWorkspace(atmosConfig schema.AtmosConfiguration, componentPath string) { filePath := filepath.Join(componentPath, ".terraform", "environment") - u.LogDebug(atmosConfig, fmt.Sprintf("\nDeleting Terraform environment file:\n'%s'", filePath)) + u.LogDebug(fmt.Sprintf("\nDeleting Terraform environment file:\n'%s'", filePath)) _ = os.Remove(filePath) } diff --git a/internal/exec/utils.go b/internal/exec/utils.go index 149e92949..88b4eb090 100644 --- a/internal/exec/utils.go +++ b/internal/exec/utils.go @@ -16,43 +16,41 @@ import ( u "github.com/cloudposse/atmos/pkg/utils" ) -var ( - // `commonFlags` are a list of flags that atmos understands but the underlying tools do not (e.g. terraform, helmfile, etc.). - // These flags get removed from the arg list after atmos uses them so the underlying tool does not get passed a flag it doesn't accept. - commonFlags = []string{ - "--stack", - "-s", - cfg.DryRunFlag, - cfg.SkipInitFlag, - cfg.KubeConfigConfigFlag, - cfg.TerraformCommandFlag, - cfg.TerraformDirFlag, - cfg.HelmfileCommandFlag, - cfg.HelmfileDirFlag, - cfg.CliConfigDirFlag, - cfg.StackDirFlag, - cfg.BasePathFlag, - cfg.VendorBasePathFlag, - cfg.GlobalOptionsFlag, - cfg.DeployRunInitFlag, - cfg.InitRunReconfigure, - cfg.AutoGenerateBackendFileFlag, - cfg.AppendUserAgentFlag, - cfg.FromPlanFlag, - cfg.PlanFileFlag, - cfg.HelpFlag1, - cfg.HelpFlag2, - cfg.WorkflowDirFlag, - cfg.JsonSchemaDirFlag, - cfg.OpaDirFlag, - cfg.CueDirFlag, - cfg.AtmosManifestJsonSchemaFlag, - cfg.RedirectStdErrFlag, - cfg.LogsLevelFlag, - cfg.LogsFileFlag, - cfg.QueryFlag, - } -) +// `commonFlags` are a list of flags that atmos understands but the underlying tools do not (e.g. terraform, helmfile, etc.). +// These flags get removed from the arg list after atmos uses them so the underlying tool does not get passed a flag it doesn't accept. +var commonFlags = []string{ + "--stack", + "-s", + cfg.DryRunFlag, + cfg.SkipInitFlag, + cfg.KubeConfigConfigFlag, + cfg.TerraformCommandFlag, + cfg.TerraformDirFlag, + cfg.HelmfileCommandFlag, + cfg.HelmfileDirFlag, + cfg.CliConfigDirFlag, + cfg.StackDirFlag, + cfg.BasePathFlag, + cfg.VendorBasePathFlag, + cfg.GlobalOptionsFlag, + cfg.DeployRunInitFlag, + cfg.InitRunReconfigure, + cfg.AutoGenerateBackendFileFlag, + cfg.AppendUserAgentFlag, + cfg.FromPlanFlag, + cfg.PlanFileFlag, + cfg.HelpFlag1, + cfg.HelpFlag2, + cfg.WorkflowDirFlag, + cfg.JsonSchemaDirFlag, + cfg.OpaDirFlag, + cfg.CueDirFlag, + cfg.AtmosManifestJsonSchemaFlag, + cfg.RedirectStdErrFlag, + cfg.LogsLevelFlag, + cfg.LogsFileFlag, + cfg.QueryFlag, +} // ProcessComponentConfig processes component config sections func ProcessComponentConfig( @@ -62,7 +60,6 @@ func ProcessComponentConfig( componentType string, component string, ) error { - var stackSection map[string]any var componentsSection map[string]any var componentTypeSection map[string]any @@ -272,7 +269,6 @@ func FindStacksMap(atmosConfig schema.AtmosConfiguration, ignoreMissingFiles boo true, ignoreMissingFiles, ) - if err != nil { return nil, nil, err } @@ -287,7 +283,6 @@ func ProcessStacks( checkStack bool, processTemplates bool, ) (schema.ConfigAndStacksInfo, error) { - // Check if stack was provided if checkStack && len(configAndStacksInfo.Stack) < 1 { message := fmt.Sprintf("'stack' is required. Usage: atmos %s -s ", configAndStacksInfo.ComponentType) @@ -315,7 +310,7 @@ func ProcessStacks( } else { msg = "\nFound stack manifests:" } - u.LogTrace(atmosConfig, msg) + u.LogTrace(msg) err = u.PrintAsYAMLToFileDescriptor(atmosConfig, atmosConfig.StackConfigFilesRelativePaths) if err != nil { return configAndStacksInfo, err @@ -331,7 +326,6 @@ func ProcessStacks( configAndStacksInfo.ComponentType, configAndStacksInfo.ComponentFromArg, ) - if err != nil { return configAndStacksInfo, err } @@ -402,7 +396,6 @@ func ProcessStacks( foundStacks = append(foundStacks, stackName) u.LogDebug( - atmosConfig, fmt.Sprintf("Found component '%s' in the stack '%s' in the stack manifest '%s'", configAndStacksInfo.ComponentFromArg, configAndStacksInfo.Stack, @@ -425,7 +418,7 @@ func ProcessStacks( } return configAndStacksInfo, - fmt.Errorf("\nCould not find the component '%s' in the stack '%s'.\n"+ + fmt.Errorf("Could not find the component '%s' in the stack '%s'.\n"+ "Check that all the context variables are correctly defined in the stack manifests.\n"+ "Are the component and stack names correct? Did you forget an import?%v\n", configAndStacksInfo.ComponentFromArg, @@ -439,7 +432,7 @@ func ProcessStacks( configAndStacksInfo.Stack, strings.Join(foundStacks, ", "), ) - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } else { configAndStacksInfo = foundConfigAndStacksInfo } @@ -521,7 +514,7 @@ func ProcessStacks( ) if err != nil { // If any error returned from the templates processing, log it and exit - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } componentSectionConverted, err := u.UnmarshalYAML[schema.AtmosSectionMapType](componentSectionProcessed) @@ -533,7 +526,7 @@ func ProcessStacks( err = errors.Join(err, errors.New(errorMessage)) } } - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } componentSectionFinal, err := ProcessCustomYamlTags(atmosConfig, componentSectionConverted, configAndStacksInfo.Stack) @@ -720,7 +713,7 @@ func processArgsAndFlags( } info.TerraformCommand = inputArgsAndFlags[i+1] } else if strings.HasPrefix(arg+"=", cfg.TerraformCommandFlag) { - var terraformCommandFlagParts = strings.Split(arg, "=") + terraformCommandFlagParts := strings.Split(arg, "=") if len(terraformCommandFlagParts) != 2 { return info, fmt.Errorf("invalid flag: %s", arg) } @@ -733,7 +726,7 @@ func processArgsAndFlags( } info.TerraformDir = inputArgsAndFlags[i+1] } else if strings.HasPrefix(arg+"=", cfg.TerraformDirFlag) { - var terraformDirFlagParts = strings.Split(arg, "=") + terraformDirFlagParts := strings.Split(arg, "=") if len(terraformDirFlagParts) != 2 { return info, fmt.Errorf("invalid flag: %s", arg) } @@ -746,7 +739,7 @@ func processArgsAndFlags( } info.AppendUserAgent = inputArgsAndFlags[i+1] } else if strings.HasPrefix(arg+"=", cfg.AppendUserAgentFlag) { - var appendUserAgentFlagParts = strings.Split(arg, "=") + appendUserAgentFlagParts := strings.Split(arg, "=") if len(appendUserAgentFlagParts) != 2 { return info, fmt.Errorf("invalid flag: %s", arg) } @@ -759,7 +752,7 @@ func processArgsAndFlags( } info.HelmfileCommand = inputArgsAndFlags[i+1] } else if strings.HasPrefix(arg+"=", cfg.HelmfileCommandFlag) { - var helmfileCommandFlagParts = strings.Split(arg, "=") + helmfileCommandFlagParts := strings.Split(arg, "=") if len(helmfileCommandFlagParts) != 2 { return info, fmt.Errorf("invalid flag: %s", arg) } @@ -772,7 +765,7 @@ func processArgsAndFlags( } info.HelmfileDir = inputArgsAndFlags[i+1] } else if strings.HasPrefix(arg+"=", cfg.HelmfileDirFlag) { - var helmfileDirFlagParts = strings.Split(arg, "=") + helmfileDirFlagParts := strings.Split(arg, "=") if len(helmfileDirFlagParts) != 2 { return info, fmt.Errorf("invalid flag: %s", arg) } @@ -785,7 +778,7 @@ func processArgsAndFlags( } info.ConfigDir = inputArgsAndFlags[i+1] } else if strings.HasPrefix(arg+"=", cfg.CliConfigDirFlag) { - var configDirFlagParts = strings.Split(arg, "=") + configDirFlagParts := strings.Split(arg, "=") if len(configDirFlagParts) != 2 { return info, fmt.Errorf("invalid flag: %s", arg) } @@ -798,7 +791,7 @@ func processArgsAndFlags( } info.StacksDir = inputArgsAndFlags[i+1] } else if strings.HasPrefix(arg+"=", cfg.StackDirFlag) { - var stacksDirFlagParts = strings.Split(arg, "=") + stacksDirFlagParts := strings.Split(arg, "=") if len(stacksDirFlagParts) != 2 { return info, fmt.Errorf("invalid flag: %s", arg) } @@ -811,7 +804,7 @@ func processArgsAndFlags( } info.BasePath = inputArgsAndFlags[i+1] } else if strings.HasPrefix(arg+"=", cfg.BasePathFlag) { - var stacksDirFlagParts = strings.Split(arg, "=") + stacksDirFlagParts := strings.Split(arg, "=") if len(stacksDirFlagParts) != 2 { return info, fmt.Errorf("invalid flag: %s", arg) } @@ -824,7 +817,7 @@ func processArgsAndFlags( } info.VendorBasePath = inputArgsAndFlags[i+1] } else if strings.HasPrefix(arg+"=", cfg.VendorBasePathFlag) { - var vendorBasePathFlagParts = strings.Split(arg, "=") + vendorBasePathFlagParts := strings.Split(arg, "=") if len(vendorBasePathFlagParts) != 2 { return info, fmt.Errorf("invalid flag: %s", arg) } @@ -837,7 +830,7 @@ func processArgsAndFlags( } info.DeployRunInit = inputArgsAndFlags[i+1] } else if strings.HasPrefix(arg+"=", cfg.DeployRunInitFlag) { - var deployRunInitFlagParts = strings.Split(arg, "=") + deployRunInitFlagParts := strings.Split(arg, "=") if len(deployRunInitFlagParts) != 2 { return info, fmt.Errorf("invalid flag: %s", arg) } @@ -850,7 +843,7 @@ func processArgsAndFlags( } info.AutoGenerateBackendFile = inputArgsAndFlags[i+1] } else if strings.HasPrefix(arg+"=", cfg.AutoGenerateBackendFileFlag) { - var autoGenerateBackendFileFlagParts = strings.Split(arg, "=") + autoGenerateBackendFileFlagParts := strings.Split(arg, "=") if len(autoGenerateBackendFileFlagParts) != 2 { return info, fmt.Errorf("invalid flag: %s", arg) } @@ -863,7 +856,7 @@ func processArgsAndFlags( } info.WorkflowsDir = inputArgsAndFlags[i+1] } else if strings.HasPrefix(arg+"=", cfg.WorkflowDirFlag) { - var workflowDirFlagParts = strings.Split(arg, "=") + workflowDirFlagParts := strings.Split(arg, "=") if len(workflowDirFlagParts) != 2 { return info, fmt.Errorf("invalid flag: %s", arg) } @@ -876,7 +869,7 @@ func processArgsAndFlags( } info.InitRunReconfigure = inputArgsAndFlags[i+1] } else if strings.HasPrefix(arg+"=", cfg.InitRunReconfigure) { - var initRunReconfigureParts = strings.Split(arg, "=") + initRunReconfigureParts := strings.Split(arg, "=") if len(initRunReconfigureParts) != 2 { return info, fmt.Errorf("invalid flag: %s", arg) } @@ -889,7 +882,7 @@ func processArgsAndFlags( } info.JsonSchemaDir = inputArgsAndFlags[i+1] } else if strings.HasPrefix(arg+"=", cfg.JsonSchemaDirFlag) { - var jsonschemaDirFlagParts = strings.Split(arg, "=") + jsonschemaDirFlagParts := strings.Split(arg, "=") if len(jsonschemaDirFlagParts) != 2 { return info, fmt.Errorf("invalid flag: %s", arg) } @@ -902,7 +895,7 @@ func processArgsAndFlags( } info.OpaDir = inputArgsAndFlags[i+1] } else if strings.HasPrefix(arg+"=", cfg.OpaDirFlag) { - var opaDirFlagParts = strings.Split(arg, "=") + opaDirFlagParts := strings.Split(arg, "=") if len(opaDirFlagParts) != 2 { return info, fmt.Errorf("invalid flag: %s", arg) } @@ -915,7 +908,7 @@ func processArgsAndFlags( } info.CueDir = inputArgsAndFlags[i+1] } else if strings.HasPrefix(arg+"=", cfg.CueDirFlag) { - var cueDirFlagParts = strings.Split(arg, "=") + cueDirFlagParts := strings.Split(arg, "=") if len(cueDirFlagParts) != 2 { return info, fmt.Errorf("invalid flag: %s", arg) } @@ -928,7 +921,7 @@ func processArgsAndFlags( } info.AtmosManifestJsonSchema = inputArgsAndFlags[i+1] } else if strings.HasPrefix(arg+"=", cfg.AtmosManifestJsonSchemaFlag) { - var atmosManifestJsonSchemaFlagParts = strings.Split(arg, "=") + atmosManifestJsonSchemaFlagParts := strings.Split(arg, "=") if len(atmosManifestJsonSchemaFlagParts) != 2 { return info, fmt.Errorf("invalid flag: %s", arg) } @@ -941,7 +934,7 @@ func processArgsAndFlags( } info.RedirectStdErr = inputArgsAndFlags[i+1] } else if strings.HasPrefix(arg+"=", cfg.RedirectStdErrFlag) { - var redirectStderrParts = strings.Split(arg, "=") + redirectStderrParts := strings.Split(arg, "=") if len(redirectStderrParts) != 2 { return info, fmt.Errorf("invalid flag: %s", arg) } @@ -955,7 +948,7 @@ func processArgsAndFlags( info.PlanFile = inputArgsAndFlags[i+1] info.UseTerraformPlan = true } else if strings.HasPrefix(arg+"=", cfg.PlanFileFlag) { - var planFileFlagParts = strings.Split(arg, "=") + planFileFlagParts := strings.Split(arg, "=") if len(planFileFlagParts) != 2 { return info, fmt.Errorf("invalid flag: %s", arg) } @@ -969,7 +962,7 @@ func processArgsAndFlags( } info.LogsLevel = inputArgsAndFlags[i+1] } else if strings.HasPrefix(arg+"=", cfg.LogsLevelFlag) { - var logsLevelFlagParts = strings.Split(arg, "=") + logsLevelFlagParts := strings.Split(arg, "=") if len(logsLevelFlagParts) != 2 { return info, fmt.Errorf("invalid flag: %s", arg) } @@ -982,7 +975,7 @@ func processArgsAndFlags( } info.LogsFile = inputArgsAndFlags[i+1] } else if strings.HasPrefix(arg+"=", cfg.LogsFileFlag) { - var logsFileFlagParts = strings.Split(arg, "=") + logsFileFlagParts := strings.Split(arg, "=") if len(logsFileFlagParts) != 2 { return info, fmt.Errorf("invalid flag: %s", arg) } @@ -995,7 +988,7 @@ func processArgsAndFlags( } info.SettingsListMergeStrategy = inputArgsAndFlags[i+1] } else if strings.HasPrefix(arg+"=", cfg.SettingsListMergeStrategyFlag) { - var settingsListMergeStrategyParts = strings.Split(arg, "=") + settingsListMergeStrategyParts := strings.Split(arg, "=") if len(settingsListMergeStrategyParts) != 2 { return info, fmt.Errorf("invalid flag: %s", arg) } @@ -1008,7 +1001,7 @@ func processArgsAndFlags( } info.Query = inputArgsAndFlags[i+1] } else if strings.HasPrefix(arg+"=", cfg.QueryFlag) { - var parts = strings.Split(arg, "=") + parts := strings.Split(arg, "=") if len(parts) != 2 { return info, fmt.Errorf("invalid flag: %s", arg) } @@ -1143,7 +1136,7 @@ func generateComponentBackendConfig(backendType string, backendConfig map[string // Generate backend config file for Terraform Cloud // https://developer.hashicorp.com/terraform/cli/cloud/settings if backendType == "cloud" { - var backendConfigFinal = backendConfig + backendConfigFinal := backendConfig if terraformWorkspace != "" { // Process template tokens in the backend config @@ -1217,7 +1210,7 @@ func FindComponentDependencies(currentStack string, sources schema.ConfigSources // getCliVars returns a map of variables provided on the command-line // atmos terraform apply template-functions-test -s tenant1-ue2-prod -var name=test2 -var stage=dev -var 'tags={"a":"value2", "Name":"test"}' func getCliVars(args []string) (map[string]any, error) { - var variables = make(map[string]any) + variables := make(map[string]any) for i := 0; i < len(args); i++ { if args[i] == "-var" && i+1 < len(args) { kv := args[i+1] diff --git a/internal/exec/validate_component.go b/internal/exec/validate_component.go index 96875bc4c..755989487 100644 --- a/internal/exec/validate_component.go +++ b/internal/exec/validate_component.go @@ -110,7 +110,7 @@ func ValidateComponent( var err error if schemaPath != "" && schemaType != "" { - u.LogDebug(atmosConfig, fmt.Sprintf("\nValidating the component '%s' using '%s' file '%s'", componentName, schemaType, schemaPath)) + u.LogDebug(fmt.Sprintf("\nValidating the component '%s' using '%s' file '%s'", componentName, schemaType, schemaPath)) ok, err = validateComponentInternal(atmosConfig, componentSection, schemaPath, schemaType, modulePaths, timeoutSeconds) if err != nil { @@ -157,10 +157,10 @@ func ValidateComponent( finalTimeoutSeconds = v.Timeout } - u.LogDebug(atmosConfig, fmt.Sprintf("\nValidating the component '%s' using '%s' file '%s'", componentName, finalSchemaType, finalSchemaPath)) + u.LogDebug(fmt.Sprintf("\nValidating the component '%s' using '%s' file '%s'", componentName, finalSchemaType, finalSchemaPath)) if v.Description != "" { - u.LogDebug(atmosConfig, v.Description) + u.LogDebug(v.Description) } ok2, err := validateComponentInternal(atmosConfig, componentSection, finalSchemaPath, finalSchemaType, finalModulePaths, finalTimeoutSeconds) diff --git a/internal/exec/validate_stacks.go b/internal/exec/validate_stacks.go index 328abcd80..7a7ff70c1 100644 --- a/internal/exec/validate_stacks.go +++ b/internal/exec/validate_stacks.go @@ -98,7 +98,7 @@ func ValidateStacks(atmosConfig schema.AtmosConfiguration) error { return err } atmosConfig.Schemas.Atmos.Manifest = f - u.LogTrace(atmosConfig, fmt.Sprintf("Atmos JSON Schema is not configured. Using the default embedded schema")) + u.LogTrace(fmt.Sprintf("Atmos JSON Schema is not configured. Using the default embedded schema")) } else if u.FileExists(atmosConfig.Schemas.Atmos.Manifest) { atmosManifestJsonSchemaFilePath = atmosConfig.Schemas.Atmos.Manifest } else if u.FileExists(atmosManifestJsonSchemaFileAbsPath) { @@ -138,7 +138,7 @@ func ValidateStacks(atmosConfig schema.AtmosConfiguration) error { return err } - u.LogDebug(atmosConfig, fmt.Sprintf("Validating all YAML files in the '%s' folder and all subfolders (excluding template files)\n", + u.LogDebug(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 { @@ -412,7 +412,7 @@ func getEmbeddedSchemaPath() (string, error) { return "", err } - err = os.WriteFile(atmosManifestJsonSchemaFilePath, embedded, 0644) + err = os.WriteFile(atmosManifestJsonSchemaFilePath, embedded, 0o644) if err != nil { return "", err } diff --git a/internal/exec/vendor_component_utils.go b/internal/exec/vendor_component_utils.go index 94088bdf1..a2e3d4dbf 100644 --- a/internal/exec/vendor_component_utils.go +++ b/internal/exec/vendor_component_utils.go @@ -127,7 +127,7 @@ func copyComponentToDestination(atmosConfig schema.AtmosConfiguration, tempDir, return true, err } else if excludeMatch { // If the file matches ANY of the 'excluded_paths' patterns, exclude the file - u.LogTrace(atmosConfig, fmt.Sprintf("Excluding the file '%s' since it matches the '%s' pattern from 'excluded_paths'\n", + u.LogTrace(fmt.Sprintf("Excluding the file '%s' since it matches the '%s' pattern from 'excluded_paths'\n", trimmedSrc, excludePath, )) @@ -145,7 +145,7 @@ func copyComponentToDestination(atmosConfig schema.AtmosConfiguration, tempDir, return true, err } else if includeMatch { // If the file matches ANY of the 'included_paths' patterns, include the file - u.LogTrace(atmosConfig, fmt.Sprintf("Including '%s' since it matches the '%s' pattern from 'included_paths'\n", + u.LogTrace(fmt.Sprintf("Including '%s' since it matches the '%s' pattern from 'included_paths'\n", trimmedSrc, includePath, )) @@ -157,13 +157,13 @@ func copyComponentToDestination(atmosConfig schema.AtmosConfiguration, tempDir, if anyMatches { return false, nil } else { - u.LogTrace(atmosConfig, fmt.Sprintf("Excluding '%s' since it does not match any pattern from 'included_paths'\n", trimmedSrc)) + u.LogTrace(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(atmosConfig, fmt.Sprintf("Including '%s'\n", u.TrimBasePathFromPath(tempDir+"/", src))) + u.LogTrace(fmt.Sprintf("Including '%s'\n", u.TrimBasePathFromPath(tempDir+"/", src))) return false, nil }, @@ -365,7 +365,7 @@ func ExecuteComponentVendorInternal( // Disable TUI if no TTY support is available if !CheckTTYSupport() { opts = []tea.ProgramOption{tea.WithoutRenderer(), tea.WithInput(nil)} - u.LogWarning(atmosConfig, "TTY is not supported. Running in non-interactive mode") + u.LogWarning("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 6ddf14e71..2fb300f49 100644 --- a/internal/exec/vendor_model.go +++ b/internal/exec/vendor_model.go @@ -140,7 +140,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.atmosConfig, errors.New(errMsg)) + u.LogError(errors.New(errMsg)) } mark = xMark m.failedPkg++ @@ -153,14 +153,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.atmosConfig, fmt.Sprintf("%s %s %s", mark, pkg.name, version)) + u.LogInfo(fmt.Sprintf("%s %s %s", mark, pkg.name, version)) if m.dryRun { - u.LogInfo(m.atmosConfig, "Done! Dry run completed. No components vendored.\n") + u.LogInfo("Done! Dry run completed. No components vendored.\n") } if m.failedPkg > 0 { - u.LogInfo(m.atmosConfig, fmt.Sprintf("Vendored %d components. Failed to vendor %d components.\n", len(m.packages)-m.failedPkg, m.failedPkg)) + u.LogInfo(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.\n", len(m.packages))) + u.LogInfo(fmt.Sprintf("Vendored %d components.\n", len(m.packages))) } version := grayColor.Render(version) return m, tea.Sequence( @@ -169,7 +169,7 @@ func (m *modelVendor) Update(msg tea.Msg) (tea.Model, tea.Cmd) { ) } if !m.isTTY { - u.LogInfo(m.atmosConfig, fmt.Sprintf("%s %s %s", mark, pkg.name, version)) + u.LogInfo(fmt.Sprintf("%s %s %s", mark, pkg.name, version)) } m.index++ // Update progress bar @@ -256,7 +256,7 @@ func downloadAndInstall(p *pkgAtmosVendor, dryRun bool, atmosConfig schema.Atmos } } // Ensure directory permissions are restricted - if err := os.Chmod(tempDir, 0700); err != nil { + if err := os.Chmod(tempDir, 0o700); err != nil { return installedPkgMsg{ err: fmt.Errorf("failed to set temp directory permissions: %w", err), name: p.name, diff --git a/internal/exec/vendor_utils.go b/internal/exec/vendor_utils.go index aa6a80c26..965538ba6 100644 --- a/internal/exec/vendor_utils.go +++ b/internal/exec/vendor_utils.go @@ -170,7 +170,7 @@ func ReadAndProcessVendorConfigFile( if !fileExists { vendorConfigFileExists = false - u.LogWarning(atmosConfig, fmt.Sprintf("Vendor config file '%s' does not exist. Proceeding without vendor configurations", pathToVendorConfig)) + u.LogWarning(fmt.Sprintf("Vendor config file '%s' does not exist. Proceeding without vendor configurations", pathToVendorConfig)) return vendorConfig, vendorConfigFileExists, "", nil } } @@ -266,7 +266,6 @@ func ExecuteAtmosVendorInternal( tags []string, dryRun bool, ) error { - var err error vendorConfigFilePath := filepath.Dir(vendorConfigFileName) @@ -421,7 +420,7 @@ 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(atmosConfig, "No TTY detected. Falling back to basic output. This can happen when no terminal is attached or when commands are pipelined.") + u.LogWarning("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, atmosConfig) @@ -489,7 +488,7 @@ func logInitialMessage(atmosConfig schema.AtmosConfiguration, vendorConfigFileNa if len(tags) > 0 { logMessage = fmt.Sprintf("%s for tags {%s}", logMessage, strings.Join(tags, ", ")) } - u.LogInfo(atmosConfig, logMessage) + u.LogInfo(logMessage) } func validateSourceFields(s *schema.AtmosVendorSource, vendorConfigFileName string) error { @@ -599,7 +598,7 @@ func generateSkipFunction(atmosConfig schema.AtmosConfiguration, tempDir string, return true, err } else if excludeMatch { // If the file matches ANY of the 'excluded_paths' patterns, exclude the file - u.LogTrace(atmosConfig, fmt.Sprintf("Excluding the file '%s' since it matches the '%s' pattern from 'excluded_paths'\n", + u.LogTrace(fmt.Sprintf("Excluding the file '%s' since it matches the '%s' pattern from 'excluded_paths'\n", trimmedSrc, excludePath, )) @@ -616,7 +615,7 @@ func generateSkipFunction(atmosConfig schema.AtmosConfiguration, tempDir string, return true, err } else if includeMatch { // If the file matches ANY of the 'included_paths' patterns, include the file - u.LogTrace(atmosConfig, fmt.Sprintf("Including '%s' since it matches the '%s' pattern from 'included_paths'\n", + u.LogTrace(fmt.Sprintf("Including '%s' since it matches the '%s' pattern from 'included_paths'\n", trimmedSrc, includePath, )) @@ -628,13 +627,13 @@ func generateSkipFunction(atmosConfig schema.AtmosConfiguration, tempDir string, if anyMatches { return false, nil } else { - u.LogTrace(atmosConfig, fmt.Sprintf("Excluding '%s' since it does not match any pattern from 'included_paths'\n", trimmedSrc)) + u.LogTrace(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(atmosConfig, fmt.Sprintf("Including '%s'\n", u.TrimBasePathFromPath(tempDir+"/", src))) + u.LogTrace(fmt.Sprintf("Including '%s'\n", u.TrimBasePathFromPath(tempDir+"/", src))) return false, nil } } diff --git a/internal/exec/workflow_utils.go b/internal/exec/workflow_utils.go index 971a06396..568e878fe 100644 --- a/internal/exec/workflow_utils.go +++ b/internal/exec/workflow_utils.go @@ -26,7 +26,7 @@ func ExecuteWorkflow( commandLineStack string, fromStep string, ) error { - var steps = workflowDefinition.Steps + steps := workflowDefinition.Steps if len(steps) == 0 { return fmt.Errorf("workflow '%s' does not have any steps defined", workflow) @@ -40,7 +40,7 @@ func ExecuteWorkflow( // Check if the workflow steps have the `name` attribute checkAndGenerateWorkflowStepNames(workflowDefinition) - logFunc(atmosConfig, fmt.Sprintf("\nExecuting the workflow '%s' from '%s'\n", workflow, workflowPath)) + logFunc(fmt.Sprintf("\nExecuting the workflow '%s' from '%s'\n", workflow, workflowPath)) if atmosConfig.Logs.Level == u.LogLevelTrace || atmosConfig.Logs.Level == u.LogLevelDebug { err := u.PrintAsYAMLToFileDescriptor(atmosConfig, workflowDefinition) @@ -61,10 +61,10 @@ func ExecuteWorkflow( } for stepIdx, step := range steps { - var command = strings.TrimSpace(step.Command) - var commandType = strings.TrimSpace(step.Type) + command := strings.TrimSpace(step.Command) + commandType := strings.TrimSpace(step.Type) - logFunc(atmosConfig, fmt.Sprintf("Executing workflow step: %s", command)) + logFunc(fmt.Sprintf("Executing workflow step: %s", command)) if commandType == "" { commandType = "atmos" @@ -77,9 +77,9 @@ func ExecuteWorkflow( } else if commandType == "atmos" { args := strings.Fields(command) - var workflowStack = strings.TrimSpace(workflowDefinition.Stack) - var stepStack = strings.TrimSpace(step.Stack) - var finalStack = "" + workflowStack := strings.TrimSpace(workflowDefinition.Stack) + stepStack := strings.TrimSpace(step.Stack) + finalStack := "" // The workflow `stack` attribute overrides the stack in the `command` (if specified) // The step `stack` attribute overrides the stack in the `command` and the workflow `stack` attribute @@ -97,7 +97,7 @@ func ExecuteWorkflow( if finalStack != "" { args = append(args, []string{"-s", finalStack}...) - logFunc(atmosConfig, fmt.Sprintf("Stack: %s", finalStack)) + logFunc(fmt.Sprintf("Stack: %s", finalStack)) } err = ExecuteShellCommand(atmosConfig, "atmos", args, ".", []string{}, dryRun, "") @@ -111,8 +111,8 @@ func ExecuteWorkflow( failedMsg := theme.Colors.Error.Sprintf("\nStep '%s' failed!", step.Name) - u.LogDebug(atmosConfig, fmt.Sprintf("\nCommand failed: %s", command)) - u.LogDebug(atmosConfig, fmt.Sprintf("Error: %v", err)) + u.LogDebug(fmt.Sprintf("\nCommand failed: %s", command)) + u.LogDebug(fmt.Sprintf("Error: %v", err)) resumeMsg := theme.Colors.Success.Sprintf( "\nTo resume the workflow from this step, run:\natmos workflow %s -f %s --from-step %s", @@ -132,7 +132,6 @@ func ExecuteWorkflow( func ExecuteDescribeWorkflows( 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) @@ -209,7 +208,7 @@ func ExecuteDescribeWorkflows( } func checkAndGenerateWorkflowStepNames(workflowDefinition *schema.WorkflowDefinition) { - var steps = workflowDefinition.Steps + steps := workflowDefinition.Steps if steps == nil { return diff --git a/internal/exec/yaml_func_env.go b/internal/exec/yaml_func_env.go index 97b33a616..139158cb1 100644 --- a/internal/exec/yaml_func_env.go +++ b/internal/exec/yaml_func_env.go @@ -15,11 +15,11 @@ func processTagEnv( input string, currentStack string, ) any { - u.LogTrace(atmosConfig, fmt.Sprintf("Executing Atmos YAML function: %s", input)) + u.LogTrace(fmt.Sprintf("Executing Atmos YAML function: %s", input)) str, err := getStringAfterTag(input, config.AtmosYamlFuncEnv) if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } var envVarName string @@ -29,7 +29,7 @@ func processTagEnv( parts, err := u.SplitStringByDelimiter(str, ' ') if err != nil { e := fmt.Errorf("error executing the YAML function: %s\n%v", input, err) - u.LogErrorAndExit(atmosConfig, e) + u.LogErrorAndExit(e) } partsLen := len(parts) @@ -41,7 +41,7 @@ func processTagEnv( envVarName = strings.TrimSpace(parts[0]) } else { err = fmt.Errorf("invalid number of arguments in the Atmos YAML function: %s. The function accepts 1 or 2 arguments", input) - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } res, envVarExists := os.LookupEnv(envVarName) diff --git a/internal/exec/yaml_func_exec.go b/internal/exec/yaml_func_exec.go index b231b9da3..927535b26 100644 --- a/internal/exec/yaml_func_exec.go +++ b/internal/exec/yaml_func_exec.go @@ -14,17 +14,16 @@ func processTagExec( input string, currentStack string, ) any { - u.LogTrace(atmosConfig, fmt.Sprintf("Executing Atmos YAML function: %s", input)) + u.LogTrace(fmt.Sprintf("Executing Atmos YAML function: %s", input)) str, err := getStringAfterTag(input, config.AtmosYamlFuncExec) - if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } res, err := ExecuteShellAndReturnOutput(atmosConfig, str, input, ".", nil, false) if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } var decoded any diff --git a/internal/exec/yaml_func_include.go b/internal/exec/yaml_func_include.go index 9dc6db8ae..4d75f3db0 100644 --- a/internal/exec/yaml_func_include.go +++ b/internal/exec/yaml_func_include.go @@ -16,10 +16,10 @@ func processTagInclude( ) any { str, err := getStringAfterTag(input, fileType) if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } - u.LogTrace(atmosConfig, fmt.Sprintf("Executing Atmos YAML function: !include %s", str)) + u.LogTrace(fmt.Sprintf("Executing Atmos YAML function: !include %s", str)) var f string q := "" @@ -27,7 +27,7 @@ func processTagInclude( parts, err := u.SplitStringByDelimiter(str, ' ') if err != nil { e := fmt.Errorf("error executing the YAML function: !include %s\n%v", str, err) - u.LogErrorAndExit(atmosConfig, e) + u.LogErrorAndExit(e) } partsLen := len(parts) @@ -39,7 +39,7 @@ func processTagInclude( f = strings.TrimSpace(parts[0]) } else { err = fmt.Errorf("invalid number of arguments in the Atmos YAML function: !include %s. The function accepts 1 or 2 arguments", str) - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } var res any @@ -52,13 +52,13 @@ func processTagInclude( if err != nil { e := fmt.Errorf("error evaluating the YAML function: !include %s\n%v", str, err) - u.LogErrorAndExit(atmosConfig, e) + u.LogErrorAndExit(e) } if q != "" { res, err = u.EvaluateYqExpression(&atmosConfig, res, q) if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } } diff --git a/internal/exec/yaml_func_store.go b/internal/exec/yaml_func_store.go index 583d3cf4a..3bd81639a 100644 --- a/internal/exec/yaml_func_store.go +++ b/internal/exec/yaml_func_store.go @@ -47,24 +47,23 @@ func processTagStore(atmosConfig schema.AtmosConfiguration, input string, curren str, err := getStringAfterTag(input, u.AtmosYamlFuncStore) if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } params, err := getParams(str, currentStack) if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } store := atmosConfig.Stores[params.storeName] if store == nil { - u.LogErrorAndExit(atmosConfig, fmt.Errorf("invalid Atmos Store YAML function execution:: %s\nstore '%s' not found", input, params.storeName)) + u.LogErrorAndExit(fmt.Errorf("invalid Atmos Store YAML function execution:: %s\nstore '%s' not found", input, params.storeName)) } value, err := store.Get(params.stack, params.component, params.key) if err != nil { - - u.LogErrorAndExit(atmosConfig, fmt.Errorf("an error occurred while looking up key %s in stack %s and component %s from store %s\n%v", params.key, params.stack, params.component, params.storeName, err)) + u.LogErrorAndExit(fmt.Errorf("an error occurred while looking up key %s in stack %s and component %s from store %s\n%v", params.key, params.stack, params.component, params.storeName, err)) } return value diff --git a/internal/exec/yaml_func_template.go b/internal/exec/yaml_func_template.go index c0ab9046a..9c6a216aa 100644 --- a/internal/exec/yaml_func_template.go +++ b/internal/exec/yaml_func_template.go @@ -14,12 +14,11 @@ func processTagTemplate( input string, currentStack string, ) any { - u.LogTrace(atmosConfig, fmt.Sprintf("Executing Atmos YAML function: %s", input)) + u.LogTrace(fmt.Sprintf("Executing Atmos YAML function: %s", input)) str, err := getStringAfterTag(input, config.AtmosYamlFuncTemplate) - if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } var decoded any diff --git a/internal/exec/yaml_func_terraform_output.go b/internal/exec/yaml_func_terraform_output.go index 7f7fd81a6..405f21cba 100644 --- a/internal/exec/yaml_func_terraform_output.go +++ b/internal/exec/yaml_func_terraform_output.go @@ -14,11 +14,11 @@ func processTagTerraformOutput( input string, currentStack string, ) any { - u.LogTrace(atmosConfig, fmt.Sprintf("Executing Atmos YAML function: %s", input)) + u.LogTrace(fmt.Sprintf("Executing Atmos YAML function: %s", input)) str, err := getStringAfterTag(input, config.AtmosYamlFuncTerraformOutput) if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } var component string @@ -38,11 +38,11 @@ func processTagTerraformOutput( component = strings.TrimSpace(parts[0]) stack = currentStack output = strings.TrimSpace(parts[1]) - u.LogTrace(atmosConfig, fmt.Sprintf("Atmos YAML function `%s` is called with two parameters 'component' and 'output'. "+ + u.LogTrace(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(atmosConfig, err) + u.LogErrorAndExit(err) } value := GetTerraformOutput(&atmosConfig, stack, component, output, false) diff --git a/main.go b/main.go index 3696f6341..ec1334c34 100644 --- a/main.go +++ b/main.go @@ -1,14 +1,18 @@ package main import ( + "github.com/charmbracelet/log" + "github.com/cloudposse/atmos/cmd" - "github.com/cloudposse/atmos/pkg/schema" u "github.com/cloudposse/atmos/pkg/utils" ) func main() { + // Disable timestamp in logs so snapshots work. We will address this in a future PR updating styles, etc. + log.Default().SetReportTimestamp(false) + err := cmd.Execute() if err != nil { - u.LogErrorAndExit(schema.AtmosConfiguration{}, err) + u.LogErrorAndExit(err) } } diff --git a/pkg/aws/aws_eks_update_kubeconfig.go b/pkg/aws/aws_eks_update_kubeconfig.go index 8a20669a5..fbb4ab242 100644 --- a/pkg/aws/aws_eks_update_kubeconfig.go +++ b/pkg/aws/aws_eks_update_kubeconfig.go @@ -10,9 +10,8 @@ import ( // https://docs.aws.amazon.com/cli/latest/reference/eks/update-kubeconfig.html func ExecuteAwsEksUpdateKubeconfig(kubeconfigContext schema.AwsEksUpdateKubeconfigContext) error { err := e.ExecuteAwsEksUpdateKubeconfig(kubeconfigContext) - if err != nil { - u.LogError(schema.AtmosConfiguration{}, err) + u.LogError(err) return err } diff --git a/pkg/component/component_processor.go b/pkg/component/component_processor.go index b2c6db215..36083dd43 100644 --- a/pkg/component/component_processor.go +++ b/pkg/component/component_processor.go @@ -16,7 +16,6 @@ func ProcessComponentInStack( atmosCliConfigPath string, atmosBasePath string, ) (map[string]any, error) { - var configAndStacksInfo schema.ConfigAndStacksInfo configAndStacksInfo.ComponentFromArg = component configAndStacksInfo.Stack = stack @@ -25,7 +24,7 @@ func ProcessComponentInStack( atmosConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) if err != nil { - u.LogError(atmosConfig, err) + u.LogError(err) return nil, err } @@ -35,7 +34,7 @@ func ProcessComponentInStack( configAndStacksInfo.ComponentType = "helmfile" configAndStacksInfo, err = e.ProcessStacks(atmosConfig, configAndStacksInfo, true, true) if err != nil { - u.LogError(atmosConfig, err) + u.LogError(err) return nil, err } } @@ -53,7 +52,6 @@ func ProcessComponentFromContext( atmosCliConfigPath string, atmosBasePath string, ) (map[string]any, error) { - var configAndStacksInfo schema.ConfigAndStacksInfo configAndStacksInfo.ComponentFromArg = component configAndStacksInfo.AtmosCliConfigPath = atmosCliConfigPath @@ -61,19 +59,19 @@ func ProcessComponentFromContext( atmosConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) if err != nil { - u.LogError(atmosConfig, err) + u.LogError(err) return nil, err } 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(atmosConfig, er) + u.LogError(er) return nil, er } stack, err := cfg.GetStackNameFromContextAndStackNamePattern(namespace, tenant, environment, stage, e.GetStackNamePattern(atmosConfig)) if err != nil { - u.LogError(atmosConfig, err) + u.LogError(err) return nil, err } diff --git a/pkg/config/cache.go b/pkg/config/cache.go index cf70ab675..f46b39a7b 100644 --- a/pkg/config/cache.go +++ b/pkg/config/cache.go @@ -12,7 +12,6 @@ import ( "github.com/pkg/errors" "github.com/spf13/viper" - "github.com/cloudposse/atmos/pkg/schema" u "github.com/cloudposse/atmos/pkg/utils" ) @@ -29,7 +28,7 @@ func GetCacheFilePath() (string, error) { cacheDir = filepath.Join(xdgCacheHome, "atmos") } - if err := os.MkdirAll(cacheDir, 0755); err != nil { + if err := os.MkdirAll(cacheDir, 0o755); err != nil { return "", errors.Wrap(err, "error creating cache directory") } @@ -105,7 +104,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.AtmosConfiguration{}, fmt.Sprintf("Unsupported frequency '%s' encountered. Defaulting to daily.", frequency)) + u.LogWarning(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 5e0f72bef..f9f95147a 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -192,7 +192,7 @@ 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(atmosConfig, fmt.Sprintf("Found ENV var ATMOS_CLI_CONFIG_PATH=%s", configFilePath4)) + u.LogTrace(fmt.Sprintf("Found ENV var ATMOS_CLI_CONFIG_PATH=%s", configFilePath4)) configFile4 := filepath.Join(configFilePath4, CliConfigFileName) found, err = processConfigFile(atmosConfig, configFile4, v) if err != nil { @@ -335,7 +335,6 @@ func InitCliConfig(configAndStacksInfo schema.ConfigAndStacksInfo, processStacks includeStackAbsPaths, excludeStackAbsPaths, ) - if err != nil { return atmosConfig, err } @@ -355,7 +354,7 @@ func InitCliConfig(configAndStacksInfo schema.ConfigAndStacksInfo, processStacks atmosConfig.StackConfigFilesRelativePaths = stackConfigFilesRelativePaths if stackIsPhysicalPath { - u.LogTrace(atmosConfig, fmt.Sprintf("\nThe stack '%s' matches the stack manifest %s\n", + u.LogTrace(fmt.Sprintf("\nThe stack '%s' matches the stack manifest %s\n", configAndStacksInfo.Stack, stackConfigFilesRelativePaths[0]), ) @@ -391,7 +390,7 @@ func processConfigFile( defer func(reader *os.File) { err := reader.Close() if err != nil { - u.LogWarning(atmosConfig, fmt.Sprintf("error closing file '"+configPath+"'. "+err.Error())) + u.LogWarning(fmt.Sprintf("error closing file '%s'. %v", configPath, err)) } }(reader) diff --git a/pkg/config/utils.go b/pkg/config/utils.go index 8d658d443..faa4a276f 100644 --- a/pkg/config/utils.go +++ b/pkg/config/utils.go @@ -22,10 +22,9 @@ func FindAllStackConfigsInPathsForStack( includeStackPaths []string, excludeStackPaths []string, ) ([]string, []string, bool, error) { - var absolutePaths []string var relativePaths []string - var stackIsDir = strings.IndexAny(stack, "/") > 0 + stackIsDir := strings.IndexAny(stack, "/") > 0 for _, p := range includeStackPaths { // Try both regular and template patterns @@ -120,7 +119,6 @@ func FindAllStackConfigsInPaths( includeStackPaths []string, excludeStackPaths []string, ) ([]string, []string, error) { - var absolutePaths []string var relativePaths []string @@ -188,61 +186,61 @@ func FindAllStackConfigsInPaths( func processEnvVars(atmosConfig *schema.AtmosConfiguration) error { basePath := os.Getenv("ATMOS_BASE_PATH") if len(basePath) > 0 { - u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_BASE_PATH=%s", basePath)) + u.LogDebug(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(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_VENDOR_BASE_PATH=%s", vendorBasePath)) + u.LogDebug(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(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_STACKS_BASE_PATH=%s", stacksBasePath)) + u.LogDebug(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(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_STACKS_INCLUDED_PATHS=%s", stacksIncludedPaths)) + u.LogDebug(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(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_STACKS_EXCLUDED_PATHS=%s", stacksExcludedPaths)) + u.LogDebug(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(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_STACKS_NAME_PATTERN=%s", stacksNamePattern)) + u.LogDebug(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(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_STACKS_NAME_TEMPLATE=%s", stacksNameTemplate)) + u.LogDebug(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(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_TERRAFORM_COMMAND=%s", componentsTerraformCommand)) + u.LogDebug(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(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_TERRAFORM_BASE_PATH=%s", componentsTerraformBasePath)) + u.LogDebug(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(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_TERRAFORM_APPLY_AUTO_APPROVE=%s", componentsTerraformApplyAutoApprove)) + u.LogDebug(fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_TERRAFORM_APPLY_AUTO_APPROVE=%s", componentsTerraformApplyAutoApprove)) applyAutoApproveBool, err := strconv.ParseBool(componentsTerraformApplyAutoApprove) if err != nil { return err @@ -252,7 +250,7 @@ func processEnvVars(atmosConfig *schema.AtmosConfiguration) error { componentsTerraformDeployRunInit := os.Getenv("ATMOS_COMPONENTS_TERRAFORM_DEPLOY_RUN_INIT") if len(componentsTerraformDeployRunInit) > 0 { - u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_TERRAFORM_DEPLOY_RUN_INIT=%s", componentsTerraformDeployRunInit)) + u.LogDebug(fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_TERRAFORM_DEPLOY_RUN_INIT=%s", componentsTerraformDeployRunInit)) deployRunInitBool, err := strconv.ParseBool(componentsTerraformDeployRunInit) if err != nil { return err @@ -262,7 +260,7 @@ func processEnvVars(atmosConfig *schema.AtmosConfiguration) error { componentsInitRunReconfigure := os.Getenv("ATMOS_COMPONENTS_TERRAFORM_INIT_RUN_RECONFIGURE") if len(componentsInitRunReconfigure) > 0 { - u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_TERRAFORM_INIT_RUN_RECONFIGURE=%s", componentsInitRunReconfigure)) + u.LogDebug(fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_TERRAFORM_INIT_RUN_RECONFIGURE=%s", componentsInitRunReconfigure)) initRunReconfigureBool, err := strconv.ParseBool(componentsInitRunReconfigure) if err != nil { return err @@ -272,7 +270,7 @@ func processEnvVars(atmosConfig *schema.AtmosConfiguration) error { componentsTerraformAutoGenerateBackendFile := os.Getenv("ATMOS_COMPONENTS_TERRAFORM_AUTO_GENERATE_BACKEND_FILE") if len(componentsTerraformAutoGenerateBackendFile) > 0 { - u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_TERRAFORM_AUTO_GENERATE_BACKEND_FILE=%s", componentsTerraformAutoGenerateBackendFile)) + u.LogDebug(fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_TERRAFORM_AUTO_GENERATE_BACKEND_FILE=%s", componentsTerraformAutoGenerateBackendFile)) componentsTerraformAutoGenerateBackendFileBool, err := strconv.ParseBool(componentsTerraformAutoGenerateBackendFile) if err != nil { return err @@ -282,19 +280,19 @@ func processEnvVars(atmosConfig *schema.AtmosConfiguration) error { componentsHelmfileCommand := os.Getenv("ATMOS_COMPONENTS_HELMFILE_COMMAND") if len(componentsHelmfileCommand) > 0 { - u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_HELMFILE_COMMAND=%s", componentsHelmfileCommand)) + u.LogDebug(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(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_HELMFILE_BASE_PATH=%s", componentsHelmfileBasePath)) + u.LogDebug(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(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_HELMFILE_USE_EKS=%s", componentsHelmfileUseEKS)) + u.LogDebug(fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_HELMFILE_USE_EKS=%s", componentsHelmfileUseEKS)) useEKSBool, err := strconv.ParseBool(componentsHelmfileUseEKS) if err != nil { return err @@ -304,61 +302,61 @@ func processEnvVars(atmosConfig *schema.AtmosConfiguration) error { componentsHelmfileKubeconfigPath := os.Getenv("ATMOS_COMPONENTS_HELMFILE_KUBECONFIG_PATH") if len(componentsHelmfileKubeconfigPath) > 0 { - u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_HELMFILE_KUBECONFIG_PATH=%s", componentsHelmfileKubeconfigPath)) + u.LogDebug(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(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_HELMFILE_HELM_AWS_PROFILE_PATTERN=%s", componentsHelmfileHelmAwsProfilePattern)) + u.LogDebug(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(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_HELMFILE_CLUSTER_NAME_PATTERN=%s", componentsHelmfileClusterNamePattern)) + u.LogDebug(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(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_WORKFLOWS_BASE_PATH=%s", workflowsBasePath)) + u.LogDebug(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(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_SCHEMAS_JSONSCHEMA_BASE_PATH=%s", jsonschemaBasePath)) + u.LogDebug(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(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_SCHEMAS_OPA_BASE_PATH=%s", opaBasePath)) + u.LogDebug(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(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_SCHEMAS_CUE_BASE_PATH=%s", cueBasePath)) + u.LogDebug(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(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_SCHEMAS_ATMOS_MANIFEST=%s", atmosManifestJsonSchemaPath)) + u.LogDebug(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(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_LOGS_FILE=%s", logsFile)) + u.LogDebug(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(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_LOGS_LEVEL=%s", logsLevel)) + u.LogDebug(fmt.Sprintf("Found ENV var ATMOS_LOGS_LEVEL=%s", logsLevel)) // Validate the log level before setting it if _, err := logger.ParseLogLevel(logsLevel); err != nil { return err @@ -369,22 +367,22 @@ func processEnvVars(atmosConfig *schema.AtmosConfiguration) error { tfAppendUserAgent := os.Getenv("ATMOS_COMPONENTS_TERRAFORM_APPEND_USER_AGENT") if len(tfAppendUserAgent) > 0 { - u.LogTrace(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_COMPONENTS_TERRAFORM_APPEND_USER_AGENT=%s", tfAppendUserAgent)) + u.LogDebug(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(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_SETTINGS_LIST_MERGE_STRATEGY=%s", listMergeStrategy)) + u.LogDebug(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(*atmosConfig, fmt.Sprintf("Found ENV var ATMOS_VERSION_CHECK_ENABLED=%s", versionEnabled)) + u.LogDebug(fmt.Sprintf("Found ENV var ATMOS_VERSION_CHECK_ENABLED=%s", versionEnabled)) enabled, err := strconv.ParseBool(versionEnabled) if err != nil { - u.LogWarning(*atmosConfig, fmt.Sprintf("Invalid boolean value '%s' for ATMOS_VERSION_CHECK_ENABLED; using default.", versionEnabled)) + u.LogWarning(fmt.Sprintf("Invalid boolean value '%s' for ATMOS_VERSION_CHECK_ENABLED; using default.", versionEnabled)) } else { atmosConfig.Version.Check.Enabled = enabled } @@ -414,31 +412,31 @@ func checkConfig(atmosConfig schema.AtmosConfiguration) error { func processCommandLineArgs(atmosConfig *schema.AtmosConfiguration, configAndStacksInfo schema.ConfigAndStacksInfo) error { if len(configAndStacksInfo.BasePath) > 0 { atmosConfig.BasePath = configAndStacksInfo.BasePath - u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s' as base path for stacks and components", configAndStacksInfo.BasePath)) + u.LogDebug(fmt.Sprintf("Using command line argument '%s' as base path for stacks and components", configAndStacksInfo.BasePath)) } if len(configAndStacksInfo.TerraformCommand) > 0 { atmosConfig.Components.Terraform.Command = configAndStacksInfo.TerraformCommand - u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s' as terraform executable", configAndStacksInfo.TerraformCommand)) + u.LogDebug(fmt.Sprintf("Using command line argument '%s' as terraform executable", configAndStacksInfo.TerraformCommand)) } if len(configAndStacksInfo.TerraformDir) > 0 { atmosConfig.Components.Terraform.BasePath = configAndStacksInfo.TerraformDir - u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s' as terraform directory", configAndStacksInfo.TerraformDir)) + u.LogDebug(fmt.Sprintf("Using command line argument '%s' as terraform directory", configAndStacksInfo.TerraformDir)) } if len(configAndStacksInfo.HelmfileCommand) > 0 { atmosConfig.Components.Helmfile.Command = configAndStacksInfo.HelmfileCommand - u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s' as helmfile executable", configAndStacksInfo.HelmfileCommand)) + u.LogDebug(fmt.Sprintf("Using command line argument '%s' as helmfile executable", configAndStacksInfo.HelmfileCommand)) } if len(configAndStacksInfo.HelmfileDir) > 0 { atmosConfig.Components.Helmfile.BasePath = configAndStacksInfo.HelmfileDir - u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s' as helmfile directory", configAndStacksInfo.HelmfileDir)) + u.LogDebug(fmt.Sprintf("Using command line argument '%s' as helmfile directory", configAndStacksInfo.HelmfileDir)) } if len(configAndStacksInfo.ConfigDir) > 0 { atmosConfig.Stacks.BasePath = configAndStacksInfo.ConfigDir - u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s' as stacks directory", configAndStacksInfo.ConfigDir)) + u.LogDebug(fmt.Sprintf("Using command line argument '%s' as stacks directory", configAndStacksInfo.ConfigDir)) } if len(configAndStacksInfo.StacksDir) > 0 { atmosConfig.Stacks.BasePath = configAndStacksInfo.StacksDir - u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s' as stacks directory", configAndStacksInfo.StacksDir)) + u.LogDebug(fmt.Sprintf("Using command line argument '%s' as stacks directory", configAndStacksInfo.StacksDir)) } if len(configAndStacksInfo.DeployRunInit) > 0 { deployRunInitBool, err := strconv.ParseBool(configAndStacksInfo.DeployRunInit) @@ -446,7 +444,7 @@ func processCommandLineArgs(atmosConfig *schema.AtmosConfiguration, configAndSta return err } atmosConfig.Components.Terraform.DeployRunInit = deployRunInitBool - u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s=%s'", DeployRunInitFlag, configAndStacksInfo.DeployRunInit)) + u.LogDebug(fmt.Sprintf("Using command line argument '%s=%s'", DeployRunInitFlag, configAndStacksInfo.DeployRunInit)) } if len(configAndStacksInfo.AutoGenerateBackendFile) > 0 { autoGenerateBackendFileBool, err := strconv.ParseBool(configAndStacksInfo.AutoGenerateBackendFile) @@ -454,11 +452,11 @@ func processCommandLineArgs(atmosConfig *schema.AtmosConfiguration, configAndSta return err } atmosConfig.Components.Terraform.AutoGenerateBackendFile = autoGenerateBackendFileBool - u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s=%s'", AutoGenerateBackendFileFlag, configAndStacksInfo.AutoGenerateBackendFile)) + u.LogDebug(fmt.Sprintf("Using command line argument '%s=%s'", AutoGenerateBackendFileFlag, configAndStacksInfo.AutoGenerateBackendFile)) } if len(configAndStacksInfo.WorkflowsDir) > 0 { atmosConfig.Workflows.BasePath = configAndStacksInfo.WorkflowsDir - u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s' as workflows directory", configAndStacksInfo.WorkflowsDir)) + u.LogDebug(fmt.Sprintf("Using command line argument '%s' as workflows directory", configAndStacksInfo.WorkflowsDir)) } if len(configAndStacksInfo.InitRunReconfigure) > 0 { initRunReconfigureBool, err := strconv.ParseBool(configAndStacksInfo.InitRunReconfigure) @@ -466,23 +464,23 @@ func processCommandLineArgs(atmosConfig *schema.AtmosConfiguration, configAndSta return err } atmosConfig.Components.Terraform.InitRunReconfigure = initRunReconfigureBool - u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s=%s'", InitRunReconfigure, configAndStacksInfo.InitRunReconfigure)) + u.LogDebug(fmt.Sprintf("Using command line argument '%s=%s'", InitRunReconfigure, configAndStacksInfo.InitRunReconfigure)) } if len(configAndStacksInfo.JsonSchemaDir) > 0 { atmosConfig.Schemas.JsonSchema.BasePath = configAndStacksInfo.JsonSchemaDir - u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s' as JsonSchema schemas directory", configAndStacksInfo.JsonSchemaDir)) + u.LogDebug(fmt.Sprintf("Using command line argument '%s' as JsonSchema schemas directory", configAndStacksInfo.JsonSchemaDir)) } if len(configAndStacksInfo.OpaDir) > 0 { atmosConfig.Schemas.Opa.BasePath = configAndStacksInfo.OpaDir - u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s' as OPA schemas directory", configAndStacksInfo.OpaDir)) + u.LogDebug(fmt.Sprintf("Using command line argument '%s' as OPA schemas directory", configAndStacksInfo.OpaDir)) } if len(configAndStacksInfo.CueDir) > 0 { atmosConfig.Schemas.Cue.BasePath = configAndStacksInfo.CueDir - u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s' as CUE schemas directory", configAndStacksInfo.CueDir)) + u.LogDebug(fmt.Sprintf("Using command line argument '%s' as CUE schemas directory", configAndStacksInfo.CueDir)) } if len(configAndStacksInfo.AtmosManifestJsonSchema) > 0 { atmosConfig.Schemas.Atmos.Manifest = configAndStacksInfo.AtmosManifestJsonSchema - u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s' as path to Atmos JSON Schema", configAndStacksInfo.AtmosManifestJsonSchema)) + u.LogDebug(fmt.Sprintf("Using command line argument '%s' as path to Atmos JSON Schema", configAndStacksInfo.AtmosManifestJsonSchema)) } if len(configAndStacksInfo.LogsLevel) > 0 { if _, err := logger.ParseLogLevel(configAndStacksInfo.LogsLevel); err != nil { @@ -490,15 +488,15 @@ func processCommandLineArgs(atmosConfig *schema.AtmosConfiguration, configAndSta } // Only set the log level if validation passes atmosConfig.Logs.Level = configAndStacksInfo.LogsLevel - u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s=%s'", LogsLevelFlag, configAndStacksInfo.LogsLevel)) + u.LogDebug(fmt.Sprintf("Using command line argument '%s=%s'", LogsLevelFlag, configAndStacksInfo.LogsLevel)) } if len(configAndStacksInfo.LogsFile) > 0 { atmosConfig.Logs.File = configAndStacksInfo.LogsFile - u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s=%s'", LogsFileFlag, configAndStacksInfo.LogsFile)) + u.LogDebug(fmt.Sprintf("Using command line argument '%s=%s'", LogsFileFlag, configAndStacksInfo.LogsFile)) } if len(configAndStacksInfo.SettingsListMergeStrategy) > 0 { atmosConfig.Settings.ListMergeStrategy = configAndStacksInfo.SettingsListMergeStrategy - u.LogTrace(*atmosConfig, fmt.Sprintf("Using command line argument '%s=%s'", SettingsListMergeStrategyFlag, configAndStacksInfo.SettingsListMergeStrategy)) + u.LogDebug(fmt.Sprintf("Using command line argument '%s=%s'", SettingsListMergeStrategyFlag, configAndStacksInfo.SettingsListMergeStrategy)) } return nil @@ -647,7 +645,6 @@ func GetStackNameFromContextAndStackNamePattern( stage string, stackNamePattern string, ) (string, error) { - if len(stackNamePattern) == 0 { return "", fmt.Errorf("stack name pattern must be provided") diff --git a/pkg/hooks/cmd.go b/pkg/hooks/cmd.go index 57c68e703..90e866c47 100644 --- a/pkg/hooks/cmd.go +++ b/pkg/hooks/cmd.go @@ -4,6 +4,7 @@ import ( "fmt" "strings" + "github.com/charmbracelet/log" e "github.com/cloudposse/atmos/internal/exec" cfg "github.com/cloudposse/atmos/pkg/config" "github.com/cloudposse/atmos/pkg/schema" @@ -36,18 +37,18 @@ func storeOutput(atmosConfig schema.AtmosConfiguration, info *schema.ConfigAndSt if store == nil { return fmt.Errorf("store %q not found in configuration", hook.Name) } - u.LogInfo(atmosConfig, fmt.Sprintf(" storing terraform output '%s' in store '%s' with key '%s' and value %v", outputKey, hook.Name, key, outputValue)) + log.Info("storing terraform output", "outputKey", outputKey, "store", hook.Name, "key", key, "value", outputValue) return store.Set(info.Stack, info.ComponentFromArg, key, outputValue) } func processStoreCommand(atmosConfig schema.AtmosConfiguration, info *schema.ConfigAndStacksInfo, hook Hook) error { if len(hook.Outputs) == 0 { - u.LogInfo(atmosConfig, fmt.Sprintf("skipping hook %q: no outputs configured", hook.Name)) + log.Info("skipping hook. no outputs configured.", "hook", hook.Name, "outputs", hook.Outputs) return nil } - u.LogInfo(atmosConfig, fmt.Sprintf("\nexecuting 'after-terraform-apply' hook '%s' with command '%s'", hook.Name, hook.Command)) + log.Info("executing 'after-terraform-apply' hook", "hook", hook.Name, "command", hook.Command) for key, value := range hook.Outputs { outputKey, outputValue := getOutputValue(atmosConfig, info, value) @@ -62,19 +63,19 @@ func processStoreCommand(atmosConfig schema.AtmosConfiguration, info *schema.Con func RunE(cmd *cobra.Command, args []string, info *schema.ConfigAndStacksInfo) error { atmosConfig, err := cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, false) if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } sections, err := e.ExecuteDescribeComponent(info.ComponentFromArg, info.Stack, true) if err != nil { - u.LogErrorAndExit(atmosConfig, err) + u.LogErrorAndExit(err) } if isTerraformApplyCommand(&info.SubCommand) { hooks := Hooks{} hooks, err = hooks.ConvertToHooks(sections["hooks"].(map[string]any)) if err != nil { - u.LogErrorAndExit(atmosConfig, fmt.Errorf("invalid hooks section %v", sections["hooks"])) + u.LogErrorAndExit(fmt.Errorf("invalid hooks section %v", sections["hooks"])) } for _, hook := range hooks { diff --git a/pkg/spacelift/spacelift_stack_processor.go b/pkg/spacelift/spacelift_stack_processor.go index 6cfd1d2c3..243014269 100644 --- a/pkg/spacelift/spacelift_stack_processor.go +++ b/pkg/spacelift/spacelift_stack_processor.go @@ -27,10 +27,9 @@ func CreateSpaceliftStacks( processImports bool, stackConfigPathTemplate string, ) (map[string]any, error) { - atmosConfig, err := cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, true) if err != nil { - u.LogError(atmosConfig, err) + u.LogError(err) return nil, err } @@ -46,7 +45,7 @@ func CreateSpaceliftStacks( false, ) if err != nil { - u.LogError(atmosConfig, err) + u.LogError(err) return nil, err } @@ -70,7 +69,7 @@ func CreateSpaceliftStacks( false, ) if err != nil { - u.LogError(atmosConfig, err) + u.LogError(err) return nil, err } @@ -94,7 +93,6 @@ func TransformStackConfigToSpaceliftStacks( processImports bool, rawStackConfigs map[string]map[string]any, ) (map[string]any, error) { - var err error res := map[string]any{} @@ -187,7 +185,7 @@ func TransformStackConfigToSpaceliftStacks( if stackNamePattern != "" { contextPrefix, err = cfg.GetContextPrefix(stackName, context, stackNamePattern, stackName) if err != nil { - u.LogError(atmosConfig, err) + u.LogError(err) return nil, err } } else { @@ -257,7 +255,7 @@ func TransformStackConfigToSpaceliftStacks( // Terraform workspace workspace, err := e.BuildTerraformWorkspace(atmosConfig, configAndStacksInfo) if err != nil { - u.LogError(atmosConfig, err) + u.LogError(err) return nil, err } spaceliftConfig["workspace"] = workspace @@ -300,7 +298,7 @@ func TransformStackConfigToSpaceliftStacks( component, ) if err != nil { - u.LogError(atmosConfig, err) + u.LogError(err) return nil, err } spaceliftStackNameDependsOnLabels1 = append(spaceliftStackNameDependsOnLabels1, fmt.Sprintf("depends-on:%s", spaceliftStackNameDependsOn)) @@ -360,7 +358,7 @@ func TransformStackConfigToSpaceliftStacks( allStackNames, ) if err != nil { - u.LogError(atmosConfig, err) + u.LogError(err) return nil, err } spaceliftStackNameDependsOnLabels2 = append(spaceliftStackNameDependsOnLabels2, fmt.Sprintf("depends-on:%s", spaceliftStackNameDependsOn)) @@ -378,7 +376,7 @@ func TransformStackConfigToSpaceliftStacks( // Spacelift stack name spaceliftStackName, spaceliftStackNamePattern, err := e.BuildSpaceliftStackName(spaceliftSettings, context, contextPrefix) if err != nil { - u.LogError(atmosConfig, err) + u.LogError(err) return nil, err } @@ -397,7 +395,7 @@ func TransformStackConfigToSpaceliftStacks( spaceliftStackNamePattern, ) er := errors.New(errorMessage) - u.LogError(atmosConfig, er) + u.LogError(er) return nil, er } } diff --git a/pkg/utils/hcl_utils.go b/pkg/utils/hcl_utils.go index bd3a6f499..aae6b1686 100644 --- a/pkg/utils/hcl_utils.go +++ b/pkg/utils/hcl_utils.go @@ -49,7 +49,7 @@ func WriteToFileAsHcl( defer func(f *os.File) { err := f.Close() if err != nil { - LogWarning(atmosConfig, err.Error()) + LogWarning(err.Error()) } }(f) @@ -122,7 +122,7 @@ func WriteTerraformBackendConfigToFileAsHcl( } } - f, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0644) + f, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0o644) if err != nil { return err } @@ -130,7 +130,7 @@ func WriteTerraformBackendConfigToFileAsHcl( defer func(f *os.File) { err := f.Close() if err != nil { - LogWarning(atmosConfig, err.Error()) + LogWarning(err.Error()) } }(f) diff --git a/pkg/utils/json_utils.go b/pkg/utils/json_utils.go index 4fe709b1a..2e6ea5f11 100644 --- a/pkg/utils/json_utils.go +++ b/pkg/utils/json_utils.go @@ -41,7 +41,7 @@ func PrintAsJSONToFileDescriptor(atmosConfig schema.AtmosConfiguration, data any if err != nil { return err } - LogInfo(atmosConfig, j) + LogInfo(j) return nil } diff --git a/pkg/utils/log_utils.go b/pkg/utils/log_utils.go index f0b665827..39d5d1ed3 100644 --- a/pkg/utils/log_utils.go +++ b/pkg/utils/log_utils.go @@ -7,7 +7,7 @@ import ( "os/exec" "runtime/debug" - "github.com/cloudposse/atmos/pkg/schema" + l "github.com/charmbracelet/log" "github.com/cloudposse/atmos/pkg/ui/theme" "github.com/fatih/color" ) @@ -35,112 +35,44 @@ func PrintErrorInColor(message string) { } // LogErrorAndExit logs errors to std.Error and exits with an error code -func LogErrorAndExit(atmosConfig schema.AtmosConfiguration, err error) { - if err != nil { - LogError(atmosConfig, err) +func LogErrorAndExit(err error) { + l.Error(err) - // Find the executed command's exit code from the error - var exitError *exec.ExitError - if errors.As(err, &exitError) { - os.Exit(exitError.ExitCode()) - } - - os.Exit(1) + // Find the executed command's exit code from the error + var exitError *exec.ExitError + if errors.As(err, &exitError) { + os.Exit(exitError.ExitCode()) } + + os.Exit(1) } // LogError logs errors to std.Error -func LogError(atmosConfig schema.AtmosConfiguration, err error) { - if err != nil { - _, printErr := theme.Colors.Error.Fprintln(color.Error, err.Error()) - if printErr != nil { - theme.Colors.Error.Println("Error logging the error:") - theme.Colors.Error.Printf("%s\n", printErr) - theme.Colors.Error.Println("Original error:") - theme.Colors.Error.Printf("%s\n", err) - } +func LogError(err error) { + l.Error(err) - // Print stack trace - if atmosConfig.Logs.Level == LogLevelTrace { - debug.PrintStack() - } + // Print stack trace + if l.GetLevel() == l.DebugLevel { + debug.PrintStack() } } // LogTrace logs the provided trace message -func LogTrace(atmosConfig schema.AtmosConfiguration, message string) { - if atmosConfig.Logs.Level == LogLevelTrace { - log(atmosConfig, theme.Colors.Info, message) - } +func LogTrace(message string) { + LogDebug(message) } // LogDebug logs the provided debug message -func LogDebug(atmosConfig schema.AtmosConfiguration, message string) { - if atmosConfig.Logs.Level == LogLevelTrace || - atmosConfig.Logs.Level == LogLevelDebug { - - log(atmosConfig, theme.Colors.Info, message) - } +func LogDebug(message string) { + l.Debug(message) } // LogInfo logs the provided info message -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 atmosConfig.Logs.Level == "" || - atmosConfig.Logs.Level == LogLevelTrace || - atmosConfig.Logs.Level == LogLevelDebug || - atmosConfig.Logs.Level == LogLevelInfo { - - log(atmosConfig, theme.Colors.Default, message) - } +func LogInfo(message string) { + l.Info(message) } // LogWarning logs the provided warning message -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(atmosConfig, theme.Colors.Warning, message) - } -} - -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 { - theme.Colors.Error.Printf("%s\n", err) - } - } else if atmosConfig.Logs.File == "/dev/stderr" { - _, err := logColor.Fprintln(os.Stderr, message) - if err != nil { - theme.Colors.Error.Printf("%s\n", err) - } - } else { - f, err := os.OpenFile(atmosConfig.Logs.File, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644) - if err != nil { - theme.Colors.Error.Printf("%s\n", err) - return - } - - defer func(f *os.File) { - err = f.Close() - if err != nil { - theme.Colors.Error.Printf("%s\n", err) - } - }(f) - - _, err = f.Write([]byte(fmt.Sprintf("%s\n", message))) - if err != nil { - theme.Colors.Error.Printf("%s\n", err) - } - } - } else { - _, err := logColor.Fprintln(os.Stdout, message) - if err != nil { - theme.Colors.Error.Printf("%s\n", err) - } - } +func LogWarning(message string) { + l.Warn(message) } diff --git a/pkg/utils/yaml_utils.go b/pkg/utils/yaml_utils.go index 4fc4c4c87..2c740b939 100644 --- a/pkg/utils/yaml_utils.go +++ b/pkg/utils/yaml_utils.go @@ -25,16 +25,14 @@ const ( AtmosYamlFuncIncludeGoGetter = "!include-go-getter" ) -var ( - AtmosYamlTags = []string{ - AtmosYamlFuncExec, - AtmosYamlFuncStore, - AtmosYamlFuncTemplate, - AtmosYamlFuncTerraformOutput, - AtmosYamlFuncEnv, - AtmosYamlFuncInclude, - } -) +var AtmosYamlTags = []string{ + AtmosYamlFuncExec, + AtmosYamlFuncStore, + AtmosYamlFuncTemplate, + AtmosYamlFuncTerraformOutput, + AtmosYamlFuncEnv, + AtmosYamlFuncInclude, +} // PrintAsYAML prints the provided value as YAML document to the console func PrintAsYAML(data any) error { @@ -60,7 +58,7 @@ func PrintAsYAMLToFileDescriptor(atmosConfig schema.AtmosConfiguration, data any if err != nil { return err } - LogInfo(atmosConfig, y) + LogInfo(y) return nil } diff --git a/pkg/validate/validate_component_test.go b/pkg/validate/validate_component_test.go index 63c4ce906..1442d5631 100644 --- a/pkg/validate/validate_component_test.go +++ b/pkg/validate/validate_component_test.go @@ -26,7 +26,7 @@ func TestValidateComponent(t *testing.T) { "opa", []string{"catalog"}, 0) - u.LogError(atmosConfig, err) + u.LogError(err) assert.Error(t, err) } @@ -45,7 +45,7 @@ func TestValidateComponent2(t *testing.T) { "", []string{"catalog/constants"}, 0) - u.LogError(atmosConfig, err) + u.LogError(err) assert.Error(t, err) } @@ -64,7 +64,7 @@ func TestValidateComponent3(t *testing.T) { "", nil, 0) - u.LogError(atmosConfig, err) + u.LogError(err) assert.Error(t, err) } @@ -83,7 +83,7 @@ func TestValidateComponent4(t *testing.T) { "", nil, 0) - u.LogError(atmosConfig, err) + u.LogError(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 26b86369b..11754d1f6 100644 --- a/pkg/validate/validate_stacks_test.go +++ b/pkg/validate/validate_stacks_test.go @@ -7,24 +7,23 @@ import ( "github.com/cloudposse/atmos/cmd" e "github.com/cloudposse/atmos/internal/exec" - "github.com/cloudposse/atmos/pkg/schema" u "github.com/cloudposse/atmos/pkg/utils" ) func TestValidateStacksCommand(t *testing.T) { err := e.ExecuteValidateStacksCmd(cmd.ValidateStacksCmd, nil) - u.LogError(schema.AtmosConfiguration{}, err) + u.LogError(err) assert.NotNil(t, err) } func TestValidateStacksCommandWithAtmosManifestJsonSchema(t *testing.T) { err := e.ExecuteValidateStacksCmd(cmd.ValidateStacksCmd, []string{"--schemas-atmos-manifest", "../../internal/exec/schemas/atmos/atmos-manifest/1.0/atmos-manifest.json"}) - u.LogError(schema.AtmosConfiguration{}, err) + u.LogError(err) assert.NotNil(t, err) } func TestValidateStacksCommandWithRemoteAtmosManifestJsonSchema(t *testing.T) { err := e.ExecuteValidateStacksCmd(cmd.ValidateStacksCmd, []string{"--schemas-atmos-manifest", "https://atmos.tools/schemas/atmos/atmos-manifest/1.0/atmos-manifest.json"}) - u.LogError(schema.AtmosConfiguration{}, err) + u.LogError(err) assert.NotNil(t, err) } diff --git a/tests/README.md b/tests/README.md index 32d49a316..4e0d14659 100644 --- a/tests/README.md +++ b/tests/README.md @@ -33,7 +33,7 @@ Smoke tests are implemented to verify the basic functionality and expected behav Our convention is to implement a test-case configuration file per scenario. Then place all smoke tests related to that scenario in the file. -### Environment Variables +### Environment Variables The tests will automatically set some environment variables: diff --git a/tests/snapshots/TestCLICommands_Invalid_Log_Level_in_Config_File.stderr.golden b/tests/snapshots/TestCLICommands_Invalid_Log_Level_in_Config_File.stderr.golden index a6a0523a5..b7302c6c6 100644 --- a/tests/snapshots/TestCLICommands_Invalid_Log_Level_in_Config_File.stderr.golden +++ b/tests/snapshots/TestCLICommands_Invalid_Log_Level_in_Config_File.stderr.golden @@ -1 +1 @@ -Error: Invalid log level 'XTrace'. Valid options are: [Trace Debug Info Warning Off] +ERRO Error: Invalid log level 'XTrace'. Valid options are: [Trace Debug Info Warning Off] diff --git a/tests/snapshots/TestCLICommands_Invalid_Log_Level_in_Environment_Variable.stderr.golden b/tests/snapshots/TestCLICommands_Invalid_Log_Level_in_Environment_Variable.stderr.golden index a6a0523a5..b7302c6c6 100644 --- a/tests/snapshots/TestCLICommands_Invalid_Log_Level_in_Environment_Variable.stderr.golden +++ b/tests/snapshots/TestCLICommands_Invalid_Log_Level_in_Environment_Variable.stderr.golden @@ -1 +1 @@ -Error: Invalid log level 'XTrace'. Valid options are: [Trace Debug Info Warning Off] +ERRO Error: Invalid log level 'XTrace'. Valid options are: [Trace Debug Info Warning Off] diff --git a/tests/snapshots/TestCLICommands_Valid_Log_Level_in_Environment_Variable.stderr.golden b/tests/snapshots/TestCLICommands_Valid_Log_Level_in_Environment_Variable.stderr.golden index e69de29bb..3844be7fe 100644 --- a/tests/snapshots/TestCLICommands_Valid_Log_Level_in_Environment_Variable.stderr.golden +++ b/tests/snapshots/TestCLICommands_Valid_Log_Level_in_Environment_Variable.stderr.golden @@ -0,0 +1,4 @@ +DEBU Found ENV var ATMOS_LOGS_LEVEL=Debug +DEBU Using command line argument '--logs-level=Info' +DEBU Using command line argument '--logs-file=/dev/stdout' +DEBU processStoreConfig atmosConfig.StoresConfig=map[] diff --git a/tests/snapshots/TestCLICommands_atmos_circuit-breaker.stderr.golden b/tests/snapshots/TestCLICommands_atmos_circuit-breaker.stderr.golden index 44f7baed6..d77d066d4 100644 --- a/tests/snapshots/TestCLICommands_atmos_circuit-breaker.stderr.golden +++ b/tests/snapshots/TestCLICommands_atmos_circuit-breaker.stderr.golden @@ -1,11 +1,11 @@ -ATMOS_SHLVL (11) exceeds maximum allowed depth (10). Infinite recursion? -exit status 1 -exit status 1 -exit status 1 -exit status 1 -exit status 1 -exit status 1 -exit status 1 -exit status 1 -exit status 1 -exit status 1 +ERRO ATMOS_SHLVL (11) exceeds maximum allowed depth (10). Infinite recursion? +ERRO exit status 1 +ERRO exit status 1 +ERRO exit status 1 +ERRO exit status 1 +ERRO exit status 1 +ERRO exit status 1 +ERRO exit status 1 +ERRO exit status 1 +ERRO exit status 1 +ERRO exit status 1 diff --git a/tests/snapshots/TestCLICommands_atmos_describe_config.stdout.golden b/tests/snapshots/TestCLICommands_atmos_describe_config.stdout.golden index 69f6586f1..3c9b7660e 100644 --- a/tests/snapshots/TestCLICommands_atmos_describe_config.stdout.golden +++ b/tests/snapshots/TestCLICommands_atmos_describe_config.stdout.golden @@ -123,15 +123,15 @@ "base_path": "" }, "initialized": true, - "stacksBaseAbsolutePath": "/Users/viniciuscardoso/Developer/atmos/examples/demo-stacks/stacks", + "stacksBaseAbsolutePath": "/Users/matt/src/github.com/cloudposse/atmos/examples/demo-stacks/stacks", "includeStackAbsolutePaths": [ - "/Users/viniciuscardoso/Developer/atmos/examples/demo-stacks/stacks/deploy/**/*" + "/Users/matt/src/github.com/cloudposse/atmos/examples/demo-stacks/stacks/deploy/**/*" ], "excludeStackAbsolutePaths": [ - "/Users/viniciuscardoso/Developer/atmos/examples/demo-stacks/stacks/**/_defaults.yaml" + "/Users/matt/src/github.com/cloudposse/atmos/examples/demo-stacks/stacks/**/_defaults.yaml" ], - "terraformDirAbsolutePath": "/Users/viniciuscardoso/Developer/atmos/examples/demo-stacks/components/terraform", - "helmfileDirAbsolutePath": "/Users/viniciuscardoso/Developer/atmos/examples/demo-stacks", + "terraformDirAbsolutePath": "/Users/matt/src/github.com/cloudposse/atmos/examples/demo-stacks/components/terraform", + "helmfileDirAbsolutePath": "/Users/matt/src/github.com/cloudposse/atmos/examples/demo-stacks", "default": false, "version": { "Check": { diff --git a/tests/snapshots/TestCLICommands_atmos_describe_config_-f_yaml.stdout.golden b/tests/snapshots/TestCLICommands_atmos_describe_config_-f_yaml.stdout.golden index 1859a7b73..de0d09a67 100644 --- a/tests/snapshots/TestCLICommands_atmos_describe_config_-f_yaml.stdout.golden +++ b/tests/snapshots/TestCLICommands_atmos_describe_config_-f_yaml.stdout.golden @@ -32,13 +32,13 @@ settings: list_merge_strategy: "" inject_github_token: true initialized: true -stacksBaseAbsolutePath: /Users/viniciuscardoso/Developer/atmos/examples/demo-stacks/stacks +stacksBaseAbsolutePath: /Users/matt/src/github.com/cloudposse/atmos/examples/demo-stacks/stacks includeStackAbsolutePaths: - - /Users/viniciuscardoso/Developer/atmos/examples/demo-stacks/stacks/deploy/**/* + - /Users/matt/src/github.com/cloudposse/atmos/examples/demo-stacks/stacks/deploy/**/* excludeStackAbsolutePaths: - - /Users/viniciuscardoso/Developer/atmos/examples/demo-stacks/stacks/**/_defaults.yaml -terraformDirAbsolutePath: /Users/viniciuscardoso/Developer/atmos/examples/demo-stacks/components/terraform -helmfileDirAbsolutePath: /Users/viniciuscardoso/Developer/atmos/examples/demo-stacks + - /Users/matt/src/github.com/cloudposse/atmos/examples/demo-stacks/stacks/**/_defaults.yaml +terraformDirAbsolutePath: /Users/matt/src/github.com/cloudposse/atmos/examples/demo-stacks/components/terraform +helmfileDirAbsolutePath: /Users/matt/src/github.com/cloudposse/atmos/examples/demo-stacks default: false validate: editorconfig: diff --git a/tests/snapshots/TestCLICommands_atmos_terraform_deploy_locked_component.stderr.golden b/tests/snapshots/TestCLICommands_atmos_terraform_deploy_locked_component.stderr.golden index 7ac58c389..89affe83a 100644 --- a/tests/snapshots/TestCLICommands_atmos_terraform_deploy_locked_component.stderr.golden +++ b/tests/snapshots/TestCLICommands_atmos_terraform_deploy_locked_component.stderr.golden @@ -1 +1 @@ -component 'myapp' is locked and cannot be modified (metadata.locked = true) +ERRO component 'myapp' is locked and cannot be modified (metadata.locked = true) diff --git a/tests/snapshots/TestCLICommands_atmos_vendor_pull_(no_tty).stderr.golden b/tests/snapshots/TestCLICommands_atmos_vendor_pull_(no_tty).stderr.golden index 3b96c511a..3f526cd52 100644 --- a/tests/snapshots/TestCLICommands_atmos_vendor_pull_(no_tty).stderr.golden +++ b/tests/snapshots/TestCLICommands_atmos_vendor_pull_(no_tty).stderr.golden @@ -1,7 +1,7 @@ -Vendoring from 'vendor.yaml' -No TTY detected. Falling back to basic output. This can happen when no terminal is attached or when commands are pipelined. -✓ github/stargazers (main) -✓ weather (main) -✓ ipinfo (main) -Vendored 3 components. +INFO Vendoring from 'vendor.yaml' +WARN No TTY detected. Falling back to basic output. This can happen when no terminal is attached or when commands are pipelined. +INFO ✓ github/stargazers (main) +INFO ✓ weather (main) +INFO ✓ ipinfo (main) +INFO Vendored 3 components. diff --git a/tests/snapshots/TestCLICommands_check_atmos_--help_in_empty-dir.stdout.golden b/tests/snapshots/TestCLICommands_check_atmos_--help_in_empty-dir.stdout.golden index bbe2d236c..02416df92 100644 --- a/tests/snapshots/TestCLICommands_check_atmos_--help_in_empty-dir.stdout.golden +++ b/tests/snapshots/TestCLICommands_check_atmos_--help_in_empty-dir.stdout.golden @@ -67,3 +67,8 @@ Example: Use "atmos [subcommand] --help" for more information about a command. +╭──────────────────────────────────────────────────────────────╮ +│ Update available! test » 1.157.0 │ +│ Atmos Releases: https://github.com/cloudposse/atmos/releases │ +│ Install Atmos: https://atmos.tools/install │ +╰──────────────────────────────────────────────────────────────╯ diff --git a/tests/test-cases/complete.yaml b/tests/test-cases/complete.yaml index e60f25386..be9acae76 100644 --- a/tests/test-cases/complete.yaml +++ b/tests/test-cases/complete.yaml @@ -12,5 +12,6 @@ tests: expect: diff: [] stderr: - - "ATMOS_SHLVL.*exceeds maximum allowed depth.*(\r?\n)+exit status 1(\r?\n)+exit status 1.*" + - 'ERRO ATMOS_SHLVL \(11\) exceeds maximum allowed depth \(10\)' + - "ERRO exit status 1" exit_code: 1 diff --git a/tests/test-cases/empty-dir.yaml b/tests/test-cases/empty-dir.yaml index 29c051d51..21845e44a 100644 --- a/tests/test-cases/empty-dir.yaml +++ b/tests/test-cases/empty-dir.yaml @@ -32,7 +32,9 @@ tests: - name: check atmos --help in empty-dir enabled: true - snapshot: true + # Snapshots are temporarily disabled until PR #957 is merged which cleans workdirs + # of files which are not part of the git repo + snapshot: false description: "Check that atmos command outputs help even with no configuration" workdir: "fixtures/scenarios/empty-dir" command: "atmos" diff --git a/tests/test-cases/log-level-validation.yaml b/tests/test-cases/log-level-validation.yaml index 18fd16ef7..c13d48fcb 100644 --- a/tests/test-cases/log-level-validation.yaml +++ b/tests/test-cases/log-level-validation.yaml @@ -70,7 +70,7 @@ tests: stdout: - '^\n👽 Atmos (\d+\.\d+\.\d+|test) on [a-z]+/[a-z0-9_]+\n\n' stderr: - - "^$" + - "DEBU Found ENV var ATMOS_LOGS_LEVEL=Debug" exit_code: 0 - name: "Valid Log Level in Command Line Flag"