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

refactor loading and checking of atmos config #869

Merged
merged 1 commit into from
Dec 19, 2024

Conversation

mcalhoun
Copy link
Member

@mcalhoun mcalhoun commented Dec 19, 2024

what

  • Refactor so that the atmos config is only loaded once and made available on the cobra command context
  • Refactor so that checkAtmosConfig is called on the root command and then only called where necessary
  • Refactor so that checkAtmosConfig takes a pointer to the atmos config, so it doesn't load it inline and doesn't have to create another copy in memory
  • Refactor CheckForAtmosUpdateAndPrintMessage to take a pointer to the atmos config so it doesn't have to create another copy in memory

why

To improve performance

references

Created this PR to replace #861 because significant refactors occurred since #861 was created, but before it was merged.

Summary by CodeRabbit

  • New Features

    • Enhanced handling of Atmos configuration across various commands by retrieving it from command context.
  • Bug Fixes

    • Improved error handling for GitHub release checks in the version command.
  • Chores

    • Removed redundant configuration checks from multiple command implementations to streamline execution flow.

@mcalhoun mcalhoun requested a review from a team as a code owner December 19, 2024 02:16
@mcalhoun mcalhoun added the no-release Do not create a new release (wait for additional code changes) label Dec 19, 2024
Copy link
Contributor

coderabbitai bot commented Dec 19, 2024

📝 Walkthrough

Walkthrough

This pull request introduces comprehensive modifications to the command execution flow across multiple files in the cmd directory. The primary changes involve removing explicit Atmos configuration checks and instead retrieving configuration from the command context. The modifications streamline command initialization, enhance context management, and simplify the error handling process across various commands like terraform, helmfile, list_stacks, and others.

Changes

File Change Summary
cmd/root.go Added context key type, modified configuration initialization to pass true, integrated context-based configuration management
cmd/cmd_utils.go Updated function signatures to handle atmosConfig as a pointer, modified error handling and configuration retrieval
Multiple Command Files Removed checkAtmosConfig() calls, retrieved atmosConfig from command context

Suggested labels

minor

Suggested reviewers

  • Gowiem
  • aknysh
  • osterman

Possibly related PRs


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 comments (4)
cmd/terraform.go (1)

Line range hint 29-29: Consider using the context-stored config for error handling.

Currently using an empty AtmosConfiguration for error logging. For consistency with the PR's objectives, consider using the context-stored config here as well.

- u.LogErrorAndExit(schema.AtmosConfiguration{}, err)
+ u.LogErrorAndExit(atmosConfig, err)

Also applies to: 42-42

cmd/vendor_pull.go (1)

Line range hint 25-25: Consider using the context-stored config for error handling.

Similar to terraform.go, consider using the retrieved atmosConfig for error logging instead of an empty configuration.

- u.LogErrorAndExit(schema.AtmosConfiguration{}, err)
+ u.LogErrorAndExit(atmosConfig, err)
cmd/version.go (1)

Line range hint 28-28: Use context-stored config for error handling.

For consistency, use the context-stored config for error logging here as well.

- u.LogErrorAndExit(schema.AtmosConfiguration{}, err)
+ atmosConfig := cmd.Context().Value(contextKey("atmos_config")).(schema.AtmosConfiguration)
+ u.LogErrorAndExit(atmosConfig, err)
cmd/cmd_utils.go (1)

Line range hint 367-383: Add nil pointer check for atmosConfig

The function now correctly accepts a pointer to optimize memory usage, but we should add a nil check before dereferencing the pointer to prevent potential panics.

 func checkAtmosConfig(atmosConfig *schema.AtmosConfiguration, opts ...AtmosValidateOption) {
+    if atmosConfig == nil {
+        os.Exit(1)
+    }
     vCfg := &ValidateConfig{
         CheckStack: true, // Default value true to check the stack
     }
🧹 Nitpick comments (5)
cmd/root.go (2)

86-86: Check for potential error-handling or logging gap
There is a blank line added at 86, probably just whitespace. If this space was introduced accidentally, consider removing for cleanliness.


99-101: Ensure no duplication of config checks
Invoking checkAtmosConfig(&atmosConfig) is logical here, although it duplicates logic found in other commands if repeated. Consider centralizing or gating additional checks to remain DRY (Don’t Repeat Yourself).

cmd/helmfile.go (1)

37-38: Pointer usage for config update checks
Passing a pointer to CheckForAtmosUpdateAndPrintMessage avoids an unnecessary copy. This is a solid move for performance and clarity, particularly if the function modifies or logs from the config object.

cmd/version.go (1)

Line range hint 34-44: Simplify GitHub release check error handling.

The error handling flow can be simplified by removing redundant checks.

 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))
-        return
-    }
-    if latestReleaseTag == "" {
-        u.LogWarning(schema.AtmosConfiguration{}, "No release information available")
-        return
-    }
+if err != nil {
+    u.LogWarning(atmosConfig, fmt.Sprintf("Failed to check for updates: %v", err))
+    return
+}
+if latestReleaseTag == "" {
+    u.LogWarning(atmosConfig, "No release information available")
+    return
+}
cmd/cmd_utils.go (1)

Line range hint 430-475: Standardize error handling style

While the pointer usage is correct, there's inconsistency in error handling. Some errors use LogWarning while others directly return. Consider standardizing the approach.

 func CheckForAtmosUpdateAndPrintMessage(atmosConfig *schema.AtmosConfiguration) {
     if !atmosConfig.Version.Check.Enabled {
         return
     }
     
     cacheCfg, err := cfg.LoadCache()
     if err != nil {
-        u.LogWarning(*atmosConfig, fmt.Sprintf("Could not load cache: %s", err))
-        return
+        return // Silent return for cache issues as they're non-critical
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fe637fa and 094ebaf.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (23)
  • cmd/atlantis_generate_repo_config.go (0 hunks)
  • cmd/cmd_utils.go (6 hunks)
  • cmd/describe_affected.go (0 hunks)
  • cmd/describe_component.go (0 hunks)
  • cmd/describe_dependents.go (0 hunks)
  • cmd/describe_stacks.go (0 hunks)
  • cmd/helmfile.go (1 hunks)
  • cmd/helmfile_generate_varfile.go (0 hunks)
  • cmd/list_components.go (1 hunks)
  • cmd/list_stacks.go (1 hunks)
  • cmd/pro_lock.go (0 hunks)
  • cmd/pro_unlock.go (0 hunks)
  • cmd/root.go (4 hunks)
  • cmd/terraform.go (1 hunks)
  • cmd/terraform_generate_backend.go (0 hunks)
  • cmd/terraform_generate_backends.go (0 hunks)
  • cmd/terraform_generate_varfile.go (0 hunks)
  • cmd/terraform_generate_varfiles.go (0 hunks)
  • cmd/validate_component.go (0 hunks)
  • cmd/validate_stacks.go (0 hunks)
  • cmd/vendor_diff.go (0 hunks)
  • cmd/vendor_pull.go (1 hunks)
  • cmd/version.go (1 hunks)
💤 Files with no reviewable changes (15)
  • cmd/pro_unlock.go
  • cmd/helmfile_generate_varfile.go
  • cmd/describe_dependents.go
  • cmd/pro_lock.go
  • cmd/describe_affected.go
  • cmd/validate_stacks.go
  • cmd/terraform_generate_backends.go
  • cmd/terraform_generate_varfile.go
  • cmd/atlantis_generate_repo_config.go
  • cmd/validate_component.go
  • cmd/terraform_generate_varfiles.go
  • cmd/describe_stacks.go
  • cmd/vendor_diff.go
  • cmd/terraform_generate_backend.go
  • cmd/describe_component.go
🧰 Additional context used
📓 Learnings (2)
cmd/version.go (1)
Learnt from: Listener430
PR: cloudposse/atmos#844
File: cmd/version.go:34-44
Timestamp: 2024-12-13T15:28:13.630Z
Learning: In `cmd/version.go`, when handling the `--check` flag in the `versionCmd`, avoid using `CheckForAtmosUpdateAndPrintMessage(cliConfig)` as it updates the cache timestamp, which may not be desired in this context.
cmd/cmd_utils.go (2)
Learnt from: Listener430
PR: cloudposse/atmos#844
File: cmd/version.go:34-44
Timestamp: 2024-12-13T15:28:13.630Z
Learning: In `cmd/version.go`, when handling the `--check` flag in the `versionCmd`, avoid using `CheckForAtmosUpdateAndPrintMessage(cliConfig)` as it updates the cache timestamp, which may not be desired in this context.
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 (9)
cmd/root.go (4)

4-4: Use of context for concurrency and cross-cutting concerns
Importing the "context" package is a great choice for passing data across function boundaries and handling potential concurrency needs. Ensure consistent usage of the context throughout the codebase, especially for any blocking or potentially long-running tasks that might benefit from cancellation or timeout.


22-23: Good practice: dedicated context key type
Defining a distinct contextKey type helps avoid key collisions and clarifies ownership of context values. This is a neat, maintainable approach.


90-90: Initialization with explicit argument
Passing "true" to InitCliConfig is a design decision that might alter initialization behavior. Verify that all callers rely on or expect this new configuration path.


102-105: Excellent use of context
Storing atmosConfig in the context fosters a more composable design. Confirm that all child commands are responsibly retrieving and handling the data, minimizing the risk of nil type assertions.

cmd/list_components.go (1)

24-24: Context-based config retrieval
Using cmd.Context().Value(...) to obtain atmosConfig streamlines initialization. Verify that type assertions never fail; consider checking for nil or errors to avoid runtime panics.

cmd/list_stacks.go (1)

25-25: Context-based atmosConfig
Grabbing atmosConfig from the context is consistent with the new pattern. Great improvement in code cohesion. Ensure that the same approach is used in all relevant commands for uniformity.

cmd/terraform.go (1)

36-37: LGTM! Proper usage of command context for config retrieval.

The change aligns with the PR's objective of using the context-stored config instead of loading it repeatedly.

cmd/vendor_pull.go (1)

20-21: LGTM! Proper implementation of pointer-based config check.

The changes align perfectly with the PR objectives by:

  1. Using context-stored config
  2. Passing config pointer to checkAtmosConfig
  3. Including stack validation as needed
cmd/version.go (1)

56-57: ⚠️ Consider the impact on cache timestamp.

Based on previous feedback, using CheckForAtmosUpdateAndPrintMessage here might unintentionally update the cache timestamp. Consider if this is the desired behavior when running the version command.

cmd/cmd_utils.go Show resolved Hide resolved
@mcalhoun mcalhoun changed the title refactor loading of atmos config refactor loading and checking of atmos config Dec 19, 2024
@mcalhoun mcalhoun requested a review from aknysh December 19, 2024 02:30
@mcalhoun mcalhoun enabled auto-merge (squash) December 19, 2024 02:35
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 @mcalhoun

@mcalhoun mcalhoun merged commit 80058a8 into main Dec 19, 2024
30 of 31 checks passed
@mcalhoun mcalhoun deleted the chore/load-atmos-config-in-root-command branch December 19, 2024 05:09
osterman added a commit that referenced this pull request Dec 23, 2024
mcalhoun added a commit that referenced this pull request Dec 23, 2024
This reverts commit 80058a8.

Co-authored-by: Erik Osterman (CEO @ Cloud Posse) <[email protected]>
Copy link

These changes were released in v1.131.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.

2 participants