Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DO NOT MERGE: Fix Terraform help printing log twice and causing error #798

Closed
wants to merge 16 commits into from

Conversation

Cerebrovinny
Copy link
Collaborator

@Cerebrovinny Cerebrovinny commented Nov 21, 2024

what

This fix Terraform help command causing logo to display twice and causes error

Evidences Test

Before:
Screenshot 2024-11-21 at 15 15 09

After 2 flags testing (--help) and (help):
Screenshot 2024-11-21 at 23 31 30

Screenshot 2024-11-21 at 23 31 48

references

Summary by CodeRabbit

  • New Features

    • Enhanced command execution flow for help commands, allowing for early exits and improved user experience when invoking help.
    • Streamlined command-line argument handling, enabling recognition of help commands without requiring additional parameters.
    • Introduced a new help flag (-help) for improved command-line assistance.
    • Simplified logo printing process with a dedicated function for the Atmos logo.
  • Bug Fixes

    • Improved error handling and validation for command execution, ensuring necessary fields are checked before processing commands.
    • Enhanced control flow and error handling in the command execution process.
  • Documentation

    • Clarified comments regarding command-line argument processing and component configurations.

@Cerebrovinny Cerebrovinny requested review from a team as code owners November 21, 2024 12:39
Copy link
Contributor

coderabbitai bot commented Nov 21, 2024

Warning

Rate limit exceeded

@Cerebrovinny has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 17 minutes and 48 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between c57977e and 2c6ba55.

📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request primarily focus on modifying the command execution flow within the Atmos CLI application. Key alterations include the removal of the checkAtmosConfig() function call in multiple command files, adjustments to the handling of the help flag, and enhancements to error handling and command-line argument processing. These updates streamline the user experience when executing commands, particularly in scenarios involving help requests.

Changes

File Change Summary
cmd/root.go Updated PersistentPreRun function to better handle help commands; added early return in Run function after error handling for styled text.
cmd/terraform.go Removed checkAtmosConfig() call in Run function; preserved command-line argument handling and error logging.
internal/exec/terraform.go Modified ExecuteTerraform to check for help commands and empty subcommands early, enhancing error handling and validation logic.
internal/exec/utils.go Enhanced processCommandLineArgs to recognize help command without component/stack; initialized component section maps in ProcessStacks to prevent nil dereference errors.
pkg/config/const.go Introduced new constant HelpFlag3 with value "-help" to expand command-line help flags.

Assessment against linked issues

Objective Addressed Explanation
Exit code 0 on successful validation (781) Changes do not ensure that usage is not printed on success.
Avoid printing logo when running atmos terraform --help (DEV-2739) The changes ensure that help commands are handled without unnecessary errors.

Possibly related PRs

Suggested reviewers

  • aknysh

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary or @auto-summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @auto-title anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (5)
cmd/terraform.go (2)

20-27: LGTM! This effectively addresses the double logo issue.

The new help detection block provides an early exit path that prevents the logo from being printed twice. This aligns perfectly with the PR objectives.

Consider making the help detection more robust with this enhancement:

-if cmd.Flags().Changed("help") || (len(args) > 0 && args[0] == "help") {
+if cmd.Flags().Changed("help") || cmd.Flags().Changed("h") || (len(args) > 0 && (args[0] == "help" || args[0] == "--help" || args[0] == "-h")) {

This would catch additional common help invocation patterns.


22-25: Consider enhancing error handling for better user experience.

The current error handling is functional but could be more specific about what went wrong during help display.

Consider wrapping the error for more context:

 err := e.ExecuteTerraformCmd(cmd, args, nil)
 if err != nil {
-    u.LogErrorAndExit(schema.CliConfiguration{}, err)
+    u.LogErrorAndExit(schema.CliConfiguration{}, fmt.Errorf("failed to display help: %w", err))
 }
cmd/root.go (3)

51-51: Early return after error is correct but redundant.

The early return after LogErrorAndExit is unnecessary since LogErrorAndExit already terminates the program. While not harmful, it's unreachable code.

Consider removing the redundant return:

- return

Line range hint 147-160: Help command may still print logo twice.

The SetHelpFunc implementation still prints the logo, which could lead to double printing in combination with other logo printing points. Based on the PR objectives to fix the double logo printing issue, we should consolidate the logo printing logic.

Consider this refactor to ensure single logo printing:

 RootCmd.SetHelpFunc(func(command *cobra.Command, strings []string) {
-		// Print a styled Atmos logo to the terminal
-		fmt.Println()
-		err := tuiUtils.PrintStyledText("ATMOS")
-		if err != nil {
-			u.LogErrorAndExit(schema.CliConfiguration{}, err)
-		}
-
 		b.HelpFunc(command, strings)
 		command.Usage()
 	})

Multiple logo printing locations identified across the codebase

The logo is printed in several locations:

  • cmd/root.go: Two instances - in the main execution and help function
  • cmd/version.go: In the version command
  • cmd/cmd_utils.go: In utility functions
  • internal/exec/terraform.go: Two instances - help and default command
  • internal/exec/helmfile.go: In default command

These multiple print locations could lead to duplicate logos appearing. A centralized approach for logo printing should be considered to maintain consistency and prevent duplicates.

🔗 Analysis chain

Line range hint 147-160: Verify logo printing across the codebase.

Let's ensure there are no other locations that might cause double logo printing.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for all potential logo printing locations
echo "Searching for logo printing calls..."
rg -l "PrintStyledText.*ATMOS" --type go

# Search for help-related functions that might trigger logo printing
echo "Searching for help-related functions..."
rg "SetHelpFunc|help.*func|RunE.*help" --type go

Length of output: 444


Script:

#!/bin/bash
# Let's examine the logo printing implementations in each file
echo "=== Logo printing in cmd/root.go ==="
rg "PrintStyledText.*ATMOS" -A 3 -B 3 cmd/root.go

echo -e "\n=== Logo printing in cmd/version.go ==="
rg "PrintStyledText.*ATMOS" -A 3 -B 3 cmd/version.go

echo -e "\n=== Logo printing in cmd/cmd_utils.go ==="
rg "PrintStyledText.*ATMOS" -A 3 -B 3 cmd/cmd_utils.go

echo -e "\n=== Logo printing in internal/exec/terraform.go ==="
rg "PrintStyledText.*ATMOS" -A 3 -B 3 internal/exec/terraform.go

echo -e "\n=== Logo printing in internal/exec/helmfile.go ==="
rg "PrintStyledText.*ATMOS" -A 3 -B 3 internal/exec/helmfile.go

Length of output: 2218

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a564308 and fccd816.

📒 Files selected for processing (3)
  • cmd/root.go (1 hunks)
  • cmd/terraform.go (1 hunks)
  • internal/exec/terraform.go (1 hunks)
🔇 Additional comments (4)
cmd/terraform.go (1)

20-27: Verify the fix resolves the double logo issue.

The implementation looks correct, but let's verify it resolves the issue completely.

✅ Verification successful

Fix successfully prevents double logo printing

The implementation is verified to be correct. The changes in cmd/terraform.go ensure that help requests are handled early, before any logo printing occurs. The flow now works as follows:

  1. Help flag check happens first in terraform command
  2. If help is requested, it directly calls ExecuteTerraformCmd and returns
  3. Logo printing only happens once through the normal command flow

The code structure prevents any possibility of double logo printing while maintaining the help functionality.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining double logo printing logic

# Search for logo printing patterns
echo "Checking for logo printing patterns..."
rg -l "PrintLogo|logo" --type go

# Search for help text display patterns
echo "Checking for help text display patterns..."
rg -l "help.*print|print.*help" --type go

Length of output: 444


Script:

#!/bin/bash
# Let's check the actual logo printing implementation and help handling

# Check logo printing in cmd/root.go
echo "=== Logo printing in cmd/root.go ==="
rg "PrintLogo" cmd/root.go -C 3

# Check help handling in internal/exec/terraform.go
echo -e "\n=== Help handling in internal/exec/terraform.go ==="
rg "help" internal/exec/terraform.go -C 3

# Check the ExecuteTerraformCmd implementation
echo -e "\n=== ExecuteTerraformCmd implementation ==="
ast-grep --pattern 'func (e *Executor) ExecuteTerraformCmd($$$) {
  $$$
}'

Length of output: 643


Script:

#!/bin/bash
# Let's examine the complete flow in cmd/terraform.go and root.go

# Check the complete terraform.go implementation
echo "=== Complete terraform.go implementation ==="
cat cmd/terraform.go

# Check the complete root.go implementation focusing on logo and help
echo -e "\n=== Root command implementation ==="
rg -B 5 -A 10 "func Execute|PrintLogo|RunE:" cmd/root.go

Length of output: 2350

cmd/root.go (1)

Line range hint 26-39: Excellent handling of help flags!

The PersistentPreRun function properly handles both help command and help flag cases, ensuring correct usage and error output behavior. This is a robust implementation that follows CLI best practices.

internal/exec/terraform.go (2)

41-49: Strong error handling implementation!

The error handling for both logo printing and help processing is thorough and follows best practices.


38-39: Verify all help command flows in the codebase

Let's ensure this change doesn't affect other help command flows.

✅ Verification successful

Help command flows are consistent and properly handled

The verification shows a consistent pattern across the codebase:

  • NeedHelp flag is properly handled in both terraform and helmfile components
  • Logo printing with PrintStyledText("ATMOS") is consistently implemented across help flows
  • Help processing is handled through the centralized processHelp function
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check all help command flows and logo printing logic

# Check for NeedHelp flag usage
echo "Checking NeedHelp flag usage:"
rg "NeedHelp" -A 3

# Check for logo printing
echo -e "\nChecking logo printing:"
rg "PrintStyledText.*ATMOS" -A 3

# Check for help processing
echo -e "\nChecking help processing:"
rg "processHelp" -A 3

Length of output: 4565

internal/exec/terraform.go Outdated Show resolved Hide resolved
coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 21, 2024
@osterman
Copy link
Member

@Cerebrovinny can you please post screenshots before/after.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (6)
pkg/config/config.go (1)

Line range hint 137-157: Consider extracting repeated error handling pattern.

The error handling pattern is repeated multiple times throughout the config file processing. Consider creating a helper function to reduce duplication.

Here's a suggested helper function:

func handleConfigFileProcessing(cliConfig schema.CliConfiguration, configFile string, v *viper.Viper) (bool, error) {
    found, err := processConfigFile(cliConfig, configFile, v)
    if err != nil {
        return false, err
    }
    return found, nil
}

This would simplify the repeated pattern to:

found, err := handleConfigFileProcessing(cliConfig, configFile1, v)
if err != nil {
    return cliConfig, err
}
if found {
    configFound = true
}
cmd/cmd_utils.go (1)

Line range hint 466-468: Consider making version command detection more robust.

While the current implementation works for direct version commands, it might be worth considering subcommands that contain 'version' as well.

Consider this more robust implementation:

-func isVersionCommand() bool {
-	return len(os.Args) > 1 && os.Args[1] == "version"
+func isVersionCommand() bool {
+	if len(os.Args) <= 1 {
+		return false
+	}
+	// Check both direct version command and subcommands
+	return os.Args[1] == "version" || (len(os.Args) > 2 && os.Args[2] == "version")
}
internal/exec/terraform.go (2)

Line range hint 42-53: Consider consolidating error handling

While the error handling is good, we can make it more concise:

-		err := tuiUtils.PrintStyledText("ATMOS")
-		if err != nil {
-			return err
-		}
-
-		err = processHelp(schema.CliConfiguration{}, "terraform", "")
-		if err != nil {
-			return err
-		}
+		if err := tuiUtils.PrintStyledText("ATMOS"); err != nil {
+			return err
+		}
+
+		if err := processHelp(schema.CliConfiguration{}, "terraform", ""); err != nil {
+			return err
+		}

62-72: Add clarifying comment for validation skip logic

The conditional validation is correct, but let's add a comment to explain why help commands skip validation:

-	// Skip stack validation for help commands
+	// Skip stack validation for help commands since they don't require a valid stack context
+	// This allows users to access help documentation even without a valid configuration
internal/exec/utils.go (2)

636-636: Enhance the comment to be more specific about command handling.

The current comment could be more descriptive about which specific commands trigger help display.

-// For commands like `atmos terraform help`, `atmos terraform clean` and `atmos terraform plan`, show the command help
+// Handle single-argument commands that should display help:
+// - Explicit help command: `atmos terraform help`
+// - Built-in commands: `atmos terraform clean`, `atmos terraform plan`
+// This prevents the logo from being displayed twice when showing help

639-645: LGTM! The help command handling logic looks solid.

The changes effectively address the double logo issue by:

  1. Explicitly handling the "help" command case
  2. Setting appropriate flags to ensure consistent help display
  3. Preventing duplicate processing that could cause the logo to appear twice

Consider fixing the indentation to be consistent with the rest of the file:

 if info.SubCommand == "help" {
   info.NeedHelp = true
   info.SubCommand = ""
   info.AdditionalArgsAndFlags = []string{"--help"}
-} else {
-  info.NeedHelp = true
-}
+  } else {
+    info.NeedHelp = true
+  }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8060b5f and 911d5a5.

📒 Files selected for processing (6)
  • cmd/cmd_utils.go (2 hunks)
  • cmd/root.go (2 hunks)
  • cmd/terraform.go (0 hunks)
  • internal/exec/terraform.go (2 hunks)
  • internal/exec/utils.go (1 hunks)
  • pkg/config/config.go (3 hunks)
💤 Files with no reviewable changes (1)
  • cmd/terraform.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/root.go
🧰 Additional context used
📓 Learnings (1)
cmd/cmd_utils.go (1)
Learnt from: osterman
PR: cloudposse/atmos#740
File: cmd/cmd_utils.go:340-359
Timestamp: 2024-11-12T05:52:05.088Z
Learning: In the Go codebase for Atmos, when reviewing functions like `checkAtmosConfig` in `cmd/cmd_utils.go`, avoid suggesting refactoring to return errors instead of calling `os.Exit` if such changes would significantly increase the scope due to the need to update multiple call sites.
🔇 Additional comments (7)
pkg/config/config.go (2)

100-107: Well done! Clean implementation of help flag detection.

The early return of defaultCliConfig when help is requested effectively prevents unnecessary config processing and resolves the double logo printing issue.


133-134: Good move on improving variable scoping.

Moving the configFound declaration closer to its usage follows Go best practices and improves code maintainability.

cmd/cmd_utils.go (2)

386-390: LGTM! Clean handling of version command.

The code appropriately suppresses the missing config message for version commands, improving the user experience.


369-376: LGTM! Early exit for help commands prevents unnecessary config validation.

The implementation correctly handles all help command variants and aligns with the PR objective of fixing the double logo printing issue.

Let's verify that we catch all help command scenarios:

✅ Verification successful

Help command handling is correctly implemented and consistent across the codebase

The implementation in cmd/cmd_utils.go aligns perfectly with the project's help command patterns. The search results confirm:

  • Help flags are consistently defined as constants (HelpFlag1="-h", HelpFlag2="--help")
  • Help detection is uniform across multiple components (cmd, internal/exec, pkg/config)
  • The early exit strategy for help commands is used consistently to prevent unnecessary operations

The implementation follows the established patterns in the codebase and correctly handles all three variants: --help, -h, and help.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify help command handling across the codebase
# Check for any other help command patterns we might have missed

rg -g '!vendor' -g '*.go' '(flag\.Bool|flag\.String|cobra.*Command).*help'

Length of output: 76


Script:

#!/bin/bash
# Let's try a broader search for help-related patterns
rg -g '!vendor' -g '*.go' -i 'help.*flag|--help|-h' -A 2 -B 2

# Also search for help command handling in main functions
ast-grep --pattern 'func main() {
  $$$
  help
  $$$
}'

# Check for any cobra command help patterns
rg -g '!vendor' -g '*.go' 'cobra.*Command.*help|help.*cobra'

Length of output: 8797

internal/exec/terraform.go (3)

38-40: Strong improvement in help detection logic!

The consolidated help check using isHelp is more comprehensive, covering both the internal flag and CLI arguments. This is a cleaner approach that prevents help-related logic from being scattered throughout the code.


56-61: Excellent optimization of config initialization!

Moving the config initialization after the help check ensures that users can access help documentation without requiring a valid configuration. This directly addresses the issue mentioned in PR objectives.


Line range hint 38-72: Verify logo printing locations

Let's ensure there are no other instances of logo printing that could cause duplication.

✅ Verification successful

Logo printing appears to be intentional in different command contexts

The logo printing in internal/exec/terraform.go is intentional and serves a specific purpose for the help command. Each instance of logo printing occurs in distinct command contexts:

  • Root command execution (cmd/root.go)
  • Help function (cmd/root.go)
  • Version command (cmd/version.go)
  • Missing config message (cmd/cmd_utils.go)
  • Terraform help (internal/exec/terraform.go)
  • Helmfile help (internal/exec/helmfile.go)

These are separate execution paths that don't overlap, ensuring the logo is printed exactly once per command execution.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other potential logo printing calls
rg "PrintStyledText.*ATMOS" --type go

Length of output: 404


Script:

#!/bin/bash
# Let's check the context around these logo prints to understand the flow
rg "PrintStyledText.*ATMOS" -B 5 -A 5 --type go

Length of output: 3224

coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 22, 2024
coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 22, 2024
coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 22, 2024
coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 22, 2024
coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 22, 2024
@Cerebrovinny Cerebrovinny marked this pull request as ready for review November 22, 2024 21:48
coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 22, 2024
@Cerebrovinny
Copy link
Collaborator Author

@osterman @aknysh this also fixes Atmos workflows showing terraform help

CleanShot 2024-11-22 at 22 15 14

@osterman osterman added the patch A minor, backward compatible change label Nov 22, 2024
@Cerebrovinny
Copy link
Collaborator Author

Screenshot 2024-12-05 at 17 18 39
Screenshot 2024-12-05 at 17 19 45
Screenshot 2024-12-05 at 17 20 08

@osterman
Copy link
Member

osterman commented Dec 5, 2024

@Cerebrovinny looks like the columns are still pinched.

@Cerebrovinny
Copy link
Collaborator Author

@Cerebrovinny looks like the columns are still pinched.

@osterman This is another PR that does not contain those fixes. Perhaps you would like to merge everything into a single PR where we can also address the style issues?

@Cerebrovinny Cerebrovinny requested a review from osterman December 5, 2024 17:28
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
internal/exec/terraform.go (1)

Line range hint 38-70: Strong architectural improvements in command flow.

The refactoring improves the command execution flow by:

  1. Clearly separating help and non-help command paths
  2. Adding proper validation gates
  3. Maintaining backward compatibility

Consider documenting these behavioral changes in the README to help users understand the improved command-line experience.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between cb30c19 and 8b52ee2.

📒 Files selected for processing (2)
  • cmd/root.go (2 hunks)
  • internal/exec/terraform.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/root.go
🔇 Additional comments (2)
internal/exec/terraform.go (2)

Line range hint 38-52: LGTM! Help command handling looks solid.

The early return pattern for help commands effectively addresses the double logo printing issue mentioned in #781. The code now properly initializes without requiring stack configuration, which aligns with the PR objectives.


53-70: Verify component validation behavior.

While the component and stack validation logic is clear, we should ensure this doesn't affect existing valid use cases.

Let's check the existing component usage patterns:

✅ Verification successful

Component validation is correctly implemented and safe.

The validation logic is consistent with the codebase's requirements and existing patterns. The checks for both component and stack being specified are fundamental validations that protect against invalid command execution. The search results show this is a core requirement across the codebase, with consistent validation patterns in multiple commands.

Key validations found:

  • Component validation is consistently required across terraform operations
  • The validation is part of the core command processing flow
  • Test coverage exists via TestValidateComponent test cases
  • The validation is used uniformly across different command handlers
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check existing component validation patterns
# Look for terraform command invocations without explicit component arguments
rg -A 3 "atmos terraform" --glob "!{*.md,*.txt}"

# Look for test cases that might be affected
rg -A 5 "TestExecuteTerraform" --glob "*_test.go"

Length of output: 83048


Script:

#!/bin/bash
# Let's check for test files and component validation patterns
fd -e go -x rg -l "TestExecuteTerraform|TestValidateComponent" {}

# Look for component validation logic in the codebase
rg -A 3 "ValidateComponent|ComponentFromArg" --glob "*.go"

# Check for component usage in workflow/command files
rg -A 3 "component.*must be specified" --glob "*.go"

Length of output: 24626

coderabbitai[bot]
coderabbitai bot previously approved these changes Dec 5, 2024
@aknysh
Copy link
Member

aknysh commented Dec 5, 2024

@Cerebrovinny

when running atmos terraform --help, two logos are still printed

when running atmos terraform help, no logo is printed

can you please review it again

@Cerebrovinny
Copy link
Collaborator Author

atmos terraform help

@aknysh thank you, still need to push changes for this case, I am also integrating tests to make sure is correct

@osterman
Copy link
Member

osterman commented Dec 5, 2024

@Cerebrovinny I was confused. You can disregard.

@aknysh brings up a good point that logo no longer is displayed on help.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (3)
internal/tui/utils/utils.go (1)

48-51: Consider restricting ResetLogoDisplay to test builds.

The reset function could lead to unexpected behavior if called in production.

Consider using build tags to restrict this to test environments:

+// +build test
+
 // ResetLogoDisplay resets the logo display flag (mainly for testing purposes)
 func ResetLogoDisplay() {
-    logoDisplayed = false
+    logoOnce = sync.Once{}
 }
cmd/root.go (2)

85-88: Consider consolidating logo printing logic.

The logo printing occurs in multiple places (Run, Execute, initConfig). This could lead to maintenance challenges.

Consider centralizing the logo printing decision:

+// shouldPrintLogo returns true if logo should be printed based on command context
+func shouldPrintLogo(cmd *cobra.Command, args []string) bool {
+    if err := cmd.ParseFlags(args); err != nil && errors.Is(err, pflag.ErrHelp) {
+        return true
+    }
+    return len(args) > 1 && (args[len(args)-1] == "help" || args[len(args)-1] == "--help")
+}

Also applies to: 91-93


Line range hint 149-154: Consider removing redundant logo printing in initConfig.

The logo is already handled in Execute and Run functions.

Remove the redundant logo printing here as it could contribute to the double-printing issue:

 RootCmd.SetHelpFunc(func(command *cobra.Command, strings []string) {
-    // Print the Atmos logo
-    err := tuiUtils.PrintAtmosLogo()
-    if err != nil {
-        u.LogErrorAndExit(schema.CliConfiguration{}, err)
-    }
     b.HelpFunc(command, strings)
     command.Usage()
 })
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6d2e119 and 036345c.

📒 Files selected for processing (4)
  • cmd/root.go (3 hunks)
  • cmd/version.go (1 hunks)
  • internal/exec/helmfile.go (1 hunks)
  • internal/tui/utils/utils.go (3 hunks)
🔇 Additional comments (5)
cmd/version.go (1)

22-23: LGTM! Clean transition to the new logo printing function.

The change from PrintStyledText to PrintAtmosLogo aligns with the goal of controlling logo display frequency.

cmd/root.go (2)

33-37: LGTM! Clean error handling with early return.

The error handling and early return pattern is well implemented.


45-62: Well-structured help command handling!

The PersistentPreRun implementation cleanly handles help command scenarios by appropriately managing usage and error silencing.

internal/exec/helmfile.go (2)

Line range hint 33-37: Verify help flag handling across different scenarios.

The early return on info.NeedHelp is clean and prevents unnecessary processing, which aligns with the PR's goal of fixing help command behavior. However, let's ensure this works consistently across different command combinations.

✅ Verification successful

Help flag handling is correctly implemented and consistent

The help flag handling in helmfile.go is properly implemented and aligns with the codebase's patterns. The verification shows:

  • Early return on NeedHelp is consistent with other command handlers
  • Help flag processing is uniform across the codebase
  • The implementation correctly prevents unnecessary processing when help is requested
  • The pattern is used consistently in both Terraform and Helmfile execution paths
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify help flag handling patterns across the codebase

# Check for consistent help flag handling
echo "Checking help flag handling patterns:"
ast-grep --pattern 'if $x.NeedHelp {
  return nil
}'

# Look for potential help-related command processing
echo "\nChecking help command processing:"
rg "processHelp.*helmfile" -A 3

Length of output: 441


Script:

#!/bin/bash
# Let's verify the complete help flag handling flow

# Check the processHelp function implementation
echo "Checking processHelp implementation:"
ast-grep --pattern 'func processHelp($$$) {
  $$$
}'

# Check all NeedHelp usages for consistency
echo "\nChecking all NeedHelp usages:"
rg "NeedHelp" -A 2 -B 2

# Check help-related command handling
echo "\nChecking help command handling:"
rg "help.*command" -A 2 -B 2

Length of output: 17259


Line range hint 42-50: LGTM! Change aligns with fixing the logo printing issue.

The switch to PrintAtmosLogo() standardizes logo printing and integrates well with the help command flow. The error handling is robust, ensuring any issues during logo printing or help processing are properly caught.

Let's verify the integration with help processing:

✅ Verification successful

Change is well-integrated and follows consistent error handling patterns

The verification confirms:

  • Logo printing is standardized using PrintAtmosLogo() across the codebase
  • Error handling is consistent with proper nil checks and error returns
  • Help command flow is properly integrated:
    • Early return on NeedHelp
    • Logo printing followed by help processing for empty subcommand
    • Proper error propagation in both logo printing and help processing
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent logo printing implementation across commands
# and verify help command integration

# Search for all logo printing calls
echo "Checking logo printing consistency:"
rg "PrintAtmosLogo|PrintStyledText.*ATMOS" -A 3

# Search for help-related error handling patterns
echo "\nChecking help command integration:"
rg "NeedHelp.*return nil" -A 5

Length of output: 1676


Script:

#!/bin/bash
# Let's verify the help command integration and error handling patterns

# Check for processHelp function implementation and usage
echo "Checking processHelp implementation:"
ast-grep --pattern 'func processHelp($$$) {
  $$$
}'

# Check for help-related patterns in helmfile.go
echo "\nChecking help patterns in helmfile.go:"
rg "help|Help" internal/exec/helmfile.go -A 3

# Check for other instances of PrintAtmosLogo to verify consistent error handling
echo "\nChecking error handling consistency:"
ast-grep --pattern 'err = tuiUtils.PrintAtmosLogo()
  if err != nil {
    $$$
  }'

Length of output: 736

internal/tui/utils/utils.go Outdated Show resolved Hide resolved
internal/tui/utils/utils.go Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (1)
internal/tui/utils/utils.go (1)

36-43: Consider adding unit tests for the new functionality.

To ensure the logo printing behavior remains correct, consider adding tests that verify:

  1. The logo is printed exactly once when called multiple times
  2. Error propagation works correctly

Would you like me to help generate unit tests for this functionality?

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 036345c and c57977e.

📒 Files selected for processing (1)
  • internal/tui/utils/utils.go (3 hunks)
🔇 Additional comments (2)
internal/tui/utils/utils.go (2)

5-7: LGTM! Clean import organization.

The sync package addition is well-placed and necessary for the thread-safe implementation.


24-25: Excellent thread-safe implementation with sync.Once!

The use of sync.Once is the correct approach for ensuring the logo is printed exactly once in a thread-safe manner.

internal/tui/utils/utils.go Show resolved Hide resolved
@aknysh aknysh marked this pull request as draft December 7, 2024 16:40
@aknysh aknysh changed the title Fix Terraform help printing log twice and causing error DO NOT MERGE: Fix Terraform help printing log twice and causing error Dec 7, 2024
@aknysh aknysh added do not merge Do not merge this PR, doing so would cause problems and removed patch A minor, backward compatible change labels Dec 7, 2024
@osterman
Copy link
Member

Let's close this for now. We can reopen if we still need it.

@osterman osterman closed this Dec 10, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
do not merge Do not merge this PR, doing so would cause problems
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

validate command prints usage when used like documented?
3 participants