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

fix exit code for each exec command #1065

Merged
merged 20 commits into from
Feb 19, 2025

Conversation

samtholiya
Copy link
Collaborator

@samtholiya samtholiya commented Feb 14, 2025

what

  • The change ensures consistency between the exit code of the CLI and the exit code of the program being executed.

why

  • Improved User Experience: It provides more accurate feedback to the user, reflecting the success or failure of the desired program.

  • Better Integration with Other Tools: Many CI/CD systems, monitoring tools, or scripts rely on exit codes to determine whether a task has succeeded or failed. Matching the exit codes allows seamless integration with existing workflows.

  • Debugging and Troubleshooting: By matching exit codes, users and developers can more easily trace issues and understand which program (or specific execution) caused the failure.

  • This change helps ensure the CLI behaves more predictably and conforms to standard practices for handling exit codes.

references

Summary by CodeRabbit

  • New Features

    • Enhanced error handling now returns exit codes that accurately reflect different command failure scenarios.
    • Introduced new configuration options for Terraform deployments, allowing simulation of various operational stages and exit statuses.
  • Tests

    • Added comprehensive test cases to verify that command executions exit with the expected codes in both successful and failing scenarios.

@mergify mergify bot added the triage Needs triage label Feb 14, 2025
@samtholiya samtholiya added the bugfix Change that restores intended behavior label Feb 14, 2025
@samtholiya samtholiya marked this pull request as ready for review February 15, 2025 11:30
@samtholiya samtholiya requested review from a team as code owners February 15, 2025 11:30
Copy link
Contributor

coderabbitai bot commented Feb 15, 2025

📝 Walkthrough

Walkthrough

This pull request enhances error handling in a Go utility by introducing logic that distinguishes exit errors from generic errors, allowing the application to exit with the appropriate code. In addition, new YAML configuration files define a Terraform deployment scenario with associated stack components and logging settings. New Terraform configuration simulates command exit codes, and updated test cases verify that the atmos command returns expected exit codes under various scenarios.

Changes

File(s) Change Summary
pkg/utils/markdown_utils.go Enhanced PrintErrorMarkdownAndExit by adding error type checks for *exec.ExitError, new imports (errors, os/exec), and adjusted exit codes.
tests/.../exitCode/atmos.yaml
tests/.../exitCode/stacks/stack.yaml
Added YAML configurations that define a Terraform deployment scenario with components, including metadata for exit codes and stage parameters.
tests/.../exec-command.yaml Introduced multiple test cases to validate that the atmos command returns the expected exit codes for various terraform plan/apply scenarios.
tests/.../terraform/exit-code/main.tf Added a Terraform module that specifies a required provider, variables (stage, exit_code), and a null_resource to simulate command exit behavior.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as Atmos Command
    participant Func as PrintErrorMarkdownAndExit
    participant ExecErr as *exec.ExitError

    Caller->>Func: Call PrintErrorMarkdownAndExit(title, error, suggestion)
    alt error is of type *exec.ExitError
        Func->>ExecErr: Retrieve exit code from error
        Func->>Caller: Exit with error's exit code
    else error is not *exec.ExitError
        Func->>Caller: Exit with default code 1
    end
Loading

Suggested reviewers

  • osterman
  • aknysh
  • mcalhoun

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 773a516 and 5b48333.

📒 Files selected for processing (2)
  • tests/fixtures/components/terraform/exit-code/main.tf (1 hunks)
  • tests/fixtures/scenarios/exitCode/atmos.yaml (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/fixtures/scenarios/exitCode/atmos.yaml
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Build (macos-latest, macos)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
  • GitHub Check: Summary
🔇 Additional comments (4)
tests/fixtures/components/terraform/exit-code/main.tf (4)

1-8: Provider Configuration is Spot On!
The configuration for the null provider is clearly defined with a suitable version constraint, ensuring consistency and compatibility.


10-14: Variable "stage" Defined Clearly
The stage variable is concisely declared with a clear description and a default value that suits its intended purpose in defining an Atmos stack.


16-20: Variable "exit_code" Set Up Properly
The exit_code variable is properly defined to simulate command exit statuses. The type declaration and default value are consistent with its usage in testing exit codes.


23-31: Resource "null_resource" is Well Structured
The null_resource utilizes a timestamp trigger to ensure it always runs, which is a clever way to force re-execution. The local-exec provisioner command "exit ${var.exit_code}" accurately simulates exit behavior, aligning nicely with the PR objectives of ensuring consistency between the CLI and program exit codes.


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 15, 2025
@mergify mergify bot removed the triage Needs triage label Feb 15, 2025
Copy link
Member

@osterman osterman left a comment

Choose a reason for hiding this comment

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

Overall looks good however we should be more precise on what we are testing. We are testing terraform exit codes.

@osterman
Copy link
Member

While we are at it, we should also test that the failed terraform apply also exits 1, and that a successful apply exits zero.

@samtholiya
Copy link
Collaborator Author

samtholiya commented Feb 15, 2025

While we are at it, we should also test that the failed terraform apply also exits 1, and that a successful apply exits zero.

Done

But a note now tests will pass only first time. I need to delete the resources so that they always, pass.
We can either do that in this pr or raise another pr because we should technically do it for all tests and i want to keep this pr short. Like we decided

@aknysh aknysh added the patch A minor, backward compatible change label Feb 15, 2025
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

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a97c72f and 34d9a73.

📒 Files selected for processing (2)
  • tests/fixtures/scenarios/exitCode/components/terraform/hook-and-store/main.tf (1 hunks)
  • tests/test-cases/exec-command.yaml (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Analyze (go)
  • GitHub Check: Summary
🔇 Additional comments (5)
tests/fixtures/scenarios/exitCode/components/terraform/hook-and-store/main.tf (3)

1-8: Provider Configuration Validated.
The new Terraform block correctly specifies the null provider with the appropriate source and version. This configuration should ensure that the required provider is fetched in line with the intended test scenarios.


10-14: Variable Declaration is Clear.
The "stage" variable is well-defined with a descriptive message and default value, making its purpose as a flag file obvious.


16-34: Valid Flag File Handling in Resource.
The null_resource "run_once" resource is implemented effectively:

  • It uses a dynamic trigger (via timestamp()) to re-run the provisioner.
  • The embedded shell script correctly checks for the existence of the file defined by the "stage" variable.
  • Exiting with code 1 when the file exists aligns with the expected failure behavior to support exit code testing.

Everything looks in order from a configuration perspective.

tests/test-cases/exec-command.yaml (2)

1-16: Terraform Plan Exit Code Test is Good.
This test case verifies that the CLI correctly passes through an exit code of 2 when executing a terraform plan with detailed exit codes. The configuration here meets the PR objective of ensuring exit code consistency.


17-31: Successful Terraform Apply Test Confirmed.
The test case expecting an exit code of 0 for a successful terraform apply is set up properly with the correct arguments and expected behavior.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 15, 2025
@aknysh
Copy link
Member

aknysh commented Feb 15, 2025

@samtholiya let me know when the PR is good for the final review

…d-store/main.tf

Co-authored-by: Andriy Knysh <aknysh@users.noreply.github.com>
…d-store/main.tf

Co-authored-by: Andriy Knysh <aknysh@users.noreply.github.com>
coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 15, 2025
coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 17, 2025
@osterman
Copy link
Member

osterman commented Feb 18, 2025

While we are at it, we should also test that the failed terraform apply also exits 1, and that a successful apply exits zero.

Done

But a note now tests will pass only first time. I need to delete the resources so that they always, pass. We can either do that in this pr or raise another pr because we should technically do it for all tests and i want to keep this pr short. Like we decided

We support a new “clean” setting in the test configuration that will delete any unstated files inside the scenario, when set to true. Use this to automatically ensure the working directory is reset when you need it to be.

@samtholiya samtholiya force-pushed the feature/dev-3051-fix-terraform-exit-code-mismatch branch from 210a477 to 6f6b236 Compare February 18, 2025 22:30
@samtholiya samtholiya force-pushed the feature/dev-3051-fix-terraform-exit-code-mismatch branch from fd13d10 to f04691a Compare February 18, 2025 22:33
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

🧹 Nitpick comments (2)
tests/fixtures/scenarios/exitCode/stacks/stack.yaml (1)

13-13: Nitpick: Missing newline at end of file.
YAMLLint reported that there is no new line character at the end on line 13. Please add a final newline to ensure compliance with YAML formatting guidelines.

🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 13-13: no new line character at the end of file

(new-line-at-end-of-file)

tests/test-cases/exec-command.yaml (1)

19-36: Test Case for Exit Code (0) Verification.
The test for terraform apply on component1 is clearly set to expect an exit code of 0. Please remove the trailing spaces on line 34, as flagged by YAMLlint, to maintain clean formatting.

🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 34-34: trailing spaces

(trailing-spaces)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 210a477 and 773a516.

📒 Files selected for processing (3)
  • tests/fixtures/scenarios/exitCode/components/terraform/exit-code/main.tf (1 hunks)
  • tests/fixtures/scenarios/exitCode/stacks/stack.yaml (1 hunks)
  • tests/test-cases/exec-command.yaml (1 hunks)
🧰 Additional context used
🪛 YAMLlint (1.35.1)
tests/fixtures/scenarios/exitCode/stacks/stack.yaml

[error] 13-13: no new line character at the end of file

(new-line-at-end-of-file)

tests/test-cases/exec-command.yaml

[error] 34-34: trailing spaces

(trailing-spaces)


[error] 52-52: trailing spaces

(trailing-spaces)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Analyze (go)
  • GitHub Check: Summary
🔇 Additional comments (8)
tests/fixtures/scenarios/exitCode/stacks/stack.yaml (1)

1-12: Good configuration for exit codes.
The structure defines the Terraform exit-code components clearly with the appropriate metadata (using component: exit-code) and variables. The separation between component1 (with only a stage) and component2 (with an explicit exit_code: 1) is clear and aligns with the intended test scenarios.

tests/fixtures/scenarios/exitCode/components/terraform/exit-code/main.tf (4)

1-8: Terraform Provider Block Looks Good.
The provider declaration for the null provider from HashiCorp is correctly configured with a version constraint of "~> 3.0".


10-14: Variable 'stage' is Well-Defined.
The stage variable has a clear description and a default value of "test", which is appropriate for simulation in test scenarios.


16-20: Variable 'exit_code' is Correctly Set Up.
The definition of the exit_code variable with type number and a default value of 0 is aligned with the requirements for simulating different exit states.


23-31: Null Resource for Exit Code Simulation is Appropriate.
The null_resource named fail_on_second_apply is configured to always run (using timestamp() as a trigger), and the local-exec provisioner correctly executes a command that exits with the value defined by var.exit_code.

tests/test-cases/exec-command.yaml (3)

2-18: Test Case for Exit Code (2) Verification.
This test case for terraform plan ensures an exit code of 2 is returned when a diff is expected (using the -detailed-exitcode flag). The inline comment clarifies the rationale for expecting exit code 2, which enhances clarity.


37-54: Test Case for Exit Code (1) Verification.
This test case for a failing terraform apply (using component2) correctly expects an exit code of 1. In addition to removing the trailing spaces on line 52, consider adding a brief inline comment explaining that the failure is due to the configuration in component2 (i.e. the variable exit_code being set to 1) for greater clarity.

🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 52-52: trailing spaces

(trailing-spaces)


1-55: Suggestion: Enhance Documentation in Test Cases.
Adding a header comment or more detailed inline notes at the top of this YAML file could help future maintainers quickly understand the differences between these test scenarios—especially clarifying why terraform plan returns exit code 2 and how the various exit codes are simulated across the components.

🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 34-34: trailing spaces

(trailing-spaces)


[error] 52-52: trailing spaces

(trailing-spaces)

Copy link
Member

@osterman osterman left a comment

Choose a reason for hiding this comment

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

LGTM!

@aknysh aknysh added no-release Do not create a new release (wait for additional code changes) and removed patch A minor, backward compatible change bugfix Change that restores intended behavior labels Feb 19, 2025
Copy link
Member

@aknysh aknysh left a comment

Choose a reason for hiding this comment

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

thanks @samtholiya

@aknysh aknysh merged commit 848bf48 into main Feb 19, 2025
46 checks passed
@aknysh aknysh deleted the feature/dev-3051-fix-terraform-exit-code-mismatch branch February 19, 2025 23:15
Copy link

These changes were released in v1.163.0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
no-release Do not create a new release (wait for additional code changes)
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants