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

increment ATMOS_SHLVL each time atmos terraform shell is called #803

Open
wants to merge 7 commits into
base: main
Choose a base branch
from

Conversation

pkbhowmick
Copy link
Collaborator

@pkbhowmick pkbhowmick commented Nov 23, 2024

what

why

references

Summary by CodeRabbit

  • New Features

    • Enhanced management of the ATMOS_SHLVL environment variable for improved shell command execution.
    • Automatic incrementing of ATMOS_SHLVL with each new shell instance to track nesting levels.
  • Documentation

    • Updated documentation for the atmos terraform shell command to clarify the new ATMOS_SHLVL functionality and its impact on shell nesting levels.

Copy link
Contributor

coderabbitai bot commented Nov 23, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request enhance the execTerraformShellCommand function in internal/exec/shell_utils.go by implementing a new management system for the ATMOS_SHLVL environment variable. This includes incrementing the variable upon each shell initiation and ensuring proper error handling. Additionally, the documentation for the atmos terraform shell command is updated to reflect these changes, clarifying how ATMOS_SHLVL tracks shell nesting levels.

Changes

File Change Summary
internal/exec/shell_utils.go Enhanced execTerraformShellCommand to manage ATMOS_SHLVL, including incrementing and error handling. Added strconv for integer conversion.
website/docs/cli/commands/terraform/terraform-shell.mdx Updated documentation for atmos terraform shell to include details on ATMOS_SHLVL management.

Assessment against linked issues

Objective Addressed Explanation
Increment ATMOS_SHLVL each time atmos terraform shell is called (DEV-2768)
Document behavior of ATMOS_SHLVL (DEV-2768)

Possibly related PRs

Suggested labels

minor, no-release

Suggested reviewers

  • osterman
  • 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 (2)
website/docs/cli/commands/terraform/terraform-shell.mdx (1)

42-44: Consider enhancing the documentation with additional details.

The documentation could be even more helpful with these additions:

  1. Add an example showing the ATMOS_SHLVL behavior:
 - If ATMOS_SHLVL is already set, it increments the value by 1 for each new shell.
+
+For example:
+```shell
+$ echo $ATMOS_SHLVL
+1
+$ atmos terraform shell component-1 -s stack-1
+$ echo $ATMOS_SHLVL
+2
+```
  1. Document what happens to ATMOS_SHLVL when exiting the shell
  2. Clarify if there's a maximum nesting level
internal/exec/shell_utils.go (1)

154-165: Consider adding bounds checking for ATMOS_SHLVL.

While the implementation correctly handles the basic case, consider adding validation for edge cases:

  1. Negative values should be normalized to 0 before incrementing
  2. Consider adding an upper bound (e.g., 1000) to prevent potential integer overflow

Here's a suggested improvement:

 atmosShellLvl := os.Getenv("ATMOS_SHLVL")
 atmosShellVal := 1
 if atmosShellLvl != "" {
     val, err := strconv.Atoi(atmosShellLvl)
     if err != nil {
         return err
     }
+    // Normalize negative values
+    if val < 0 {
+        val = 0
+    }
+    // Prevent integer overflow
+    if val >= 1000 {
+        return fmt.Errorf("ATMOS_SHLVL value too high: %d", val)
+    }
     atmosShellVal = val + 1
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4b30800 and 17207f4.

📒 Files selected for processing (2)
  • internal/exec/shell_utils.go (2 hunks)
  • website/docs/cli/commands/terraform/terraform-shell.mdx (1 hunks)
🔇 Additional comments (3)
website/docs/cli/commands/terraform/terraform-shell.mdx (1)

42-44: LGTM! Clear and concise documentation of the ATMOS_SHLVL behavior.

The documentation effectively explains how the ATMOS_SHLVL environment variable tracks shell nesting levels, making it clear for users to understand the behavior.

internal/exec/shell_utils.go (2)

12-12: LGTM! Clean import addition.

The strconv import is correctly placed and necessary for the new ATMOS_SHLVL parsing functionality.


154-171: Verify test coverage and usage.

Let's ensure proper test coverage exists and check for other uses of ATMOS_SHLVL:

internal/exec/shell_utils.go Outdated Show resolved Hide resolved
Signed-off-by: Pulak Kanti Bhowmick <[email protected]>
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/shell_utils.go (1)

154-186: Consider extracting ATMOS_SHLVL management into helper functions.

The ATMOS_SHLVL management logic could be more modular and reusable. Consider extracting it into helper functions:

+// incrementAtmosShellLevel increments ATMOS_SHLVL and returns any error
+func incrementAtmosShellLevel() error {
+    atmosShellLvl := os.Getenv("ATMOS_SHLVL")
+    atmosShellVal := 1
+    if atmosShellLvl != "" {
+        val, err := strconv.Atoi(atmosShellLvl)
+        if err != nil {
+            return err
+        }
+        atmosShellVal = val + 1
+    }
+    return os.Setenv("ATMOS_SHLVL", fmt.Sprintf("%d", atmosShellVal))
+}
+
+// decrementAtmosShellLevel decrements ATMOS_SHLVL and logs any errors
+func decrementAtmosShellLevel(cliConfig schema.CliConfiguration) {
+    atmosShellLvl := os.Getenv("ATMOS_SHLVL")
+    if atmosShellLvl == "" {
+        return
+    }
+    val, err := strconv.Atoi(atmosShellLvl)
+    if err != nil {
+        u.LogWarning(cliConfig, fmt.Sprintf("Failed to parse ATMOS_SHLVL: %v", err))
+        return
+    }
+    newVal := val - 1
+    if newVal < 0 {
+        newVal = 0
+    }
+    if err := os.Setenv("ATMOS_SHLVL", fmt.Sprintf("%d", newVal)); err != nil {
+        u.LogWarning(cliConfig, fmt.Sprintf("Failed to update ATMOS_SHLVL: %v", err))
+    }
+}

Then in execTerraformShellCommand:

-    atmosShellLvl := os.Getenv("ATMOS_SHLVL")
-    atmosShellVal := 1
-    if atmosShellLvl != "" {
-        val, err := strconv.Atoi(atmosShellLvl)
-        if err != nil {
-            return err
-        }
-        atmosShellVal = val + 1
-    }
-    if err := os.Setenv("ATMOS_SHLVL", fmt.Sprintf("%d", atmosShellVal)); err != nil {
-        return err
-    }
+    if err := incrementAtmosShellLevel(); err != nil {
+        return err
+    }

     // decrement the value after exiting the shell
     defer func() {
-        atmosShellLvl := os.Getenv("ATMOS_SHLVL")
-        if atmosShellLvl == "" {
-            return
-        }
-        val, err := strconv.Atoi(atmosShellLvl)
-        if err != nil {
-            u.LogWarning(cliConfig, fmt.Sprintf("Failed to parse ATMOS_SHLVL: %v", err))
-            return
-        }
-        newVal := val - 1
-        if newVal < 0 {
-            newVal = 0
-        }
-        if err := os.Setenv("ATMOS_SHLVL", fmt.Sprintf("%d", newVal)); err != nil {
-            u.LogWarning(cliConfig, fmt.Sprintf("Failed to update ATMOS_SHLVL: %v", err))
-        }
+        decrementAtmosShellLevel(cliConfig)
     }()

This refactoring would:

  1. Make the code more maintainable and reusable
  2. Simplify testing of the ATMOS_SHLVL logic
  3. Improve readability of the main function
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 17207f4 and 5ed2ad7.

📒 Files selected for processing (1)
  • internal/exec/shell_utils.go (2 hunks)
🔇 Additional comments (2)
internal/exec/shell_utils.go (2)

167-186: Excellent implementation of error handling in defer block!

The code successfully addresses all the concerns raised in the previous review:

  • Proper error handling for parsing ATMOS_SHLVL
  • Prevention of negative values
  • Warning logs for errors
  • Early returns on invalid states

154-165: LGTM! Implementation matches Bash's SHLVL behavior.

The code correctly handles the ATMOS_SHLVL initialization and increment logic with proper error handling.

Let's verify that the behavior matches Bash's SHLVL:

✅ Verification successful

ATMOS_SHLVL implementation is correct and well-documented

The implementation perfectly aligns with the documented behavior in the docs:

  • Initializes to 1 when not set
  • Increments by 1 for each new shell
  • Includes proper error handling and cleanup

The code matches the documented behavior in website/docs/cli/commands/terraform/terraform-shell.mdx, and the implementation in internal/exec/shell_utils.go follows the same pattern as Bash's SHLVL, making it familiar to users.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Compare ATMOS_SHLVL behavior with Bash's SHLVL
# Test: Search for SHLVL usage in shell scripts to understand standard patterns
rg -g '*.sh' 'SHLVL' -A 3 -B 3

Length of output: 30


Script:

#!/bin/bash
# Let's verify the ATMOS_SHLVL implementation by checking:
# 1. All references to ATMOS_SHLVL in the codebase
# 2. The shell execution context where it's used
# 3. Any tests that verify this behavior

# Search for all ATMOS_SHLVL references
echo "=== ATMOS_SHLVL References ==="
rg "ATMOS_SHLVL"

# Check the shell execution context
echo -e "\n=== Shell Execution Context ==="
ast-grep --pattern 'func execTerraformShellCommand($$$) {
    $$$
}'

# Look for related test files
echo -e "\n=== Related Test Files ==="
fd "shell.*test\.go$"

Length of output: 1297

coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 23, 2024
@osterman
Copy link
Member

osterman commented Nov 24, 2024

@pkbhowmick please add screenshots to demonstrate functionality

@pkbhowmick
Copy link
Collaborator Author

image

Here is the working demo @osterman

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants