Skip to content

chore: errors block processing simplification #4046

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

Merged
merged 13 commits into from
Mar 28, 2025
Merged

Conversation

denis256
Copy link
Member

@denis256 denis256 commented Mar 19, 2025

Description

Simplified code for processing errors block

TODOs

Read the Gruntwork contribution guidelines.

  • Update the docs.
  • Run the relevant tests successfully, including pre-commit checks.
  • Ensure any 3rd party code adheres with our license policy or delete this line if its not applicable.
  • Include release notes. If this PR is backward incompatible, include a migration guide.

Release Notes (draft)

Added / Removed / Updated [X].

Migration Guide

Summary by CodeRabbit

  • New Features

    • Enhanced error handling by enabling seamless combination of configuration settings, allowing for more robust management of error responses.
    • Introduced a new utility function for converting map data into an ordered list format, streamlining data processing.
  • Bug Fixes

    • Simplified error handling logic by removing unnecessary comments, maintaining the same control flow and error checks.
  • Style

    • Improved code readability by adding blank lines for better separation of logical blocks in the error handling sections.
  • Tests

    • Added new test coverage for the MapToSlice function, validating behavior with empty and single-element maps.

Copy link

vercel bot commented Mar 19, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
terragrunt-docs ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 28, 2025 3:30pm

Copy link
Contributor

coderabbitai bot commented Mar 19, 2025

📝 Walkthrough

Walkthrough

The changes modify the error configuration handling by enhancing deep copy and merge functionalities. In config/errors_block.go, a new Merge method is introduced for combining ErrorsConfig instances while updating fields using helper functions. Additional Clone methods for RetryBlock and IgnoreBlock and several helper functions for cloning and merging slices and maps have been added or updated. In util/collections.go, a generic MapToSlice function is implemented to convert map values into a slice. These updates affect several exported methods and helper functions.

Changes

File(s) Summary of Changes
config/errors_block.go - Clone Enhancements: Updated ErrorsConfig.Clone comment; added Clone methods for RetryBlock and IgnoreBlock.
- Merge Functionality: Added Merge method for ErrorsConfig with helper functions mergeRetryBlocks and mergeIgnoreBlocks.
- Helper Functions: Introduced cloneRetryBlocks, cloneIgnoreBlocks, cloneStringSlice, and cloneSignalsMap for deep copying.
util/collections.go - New Utility: Added generic function MapToSlice[T any](m map[string]*T) []*T to convert map values to a slice.
config/config.go - Code Simplification: Removed commented-out line in decodeAsTerragruntConfigFile for clearer error handling.
cli/commands/backend/bootstrap/bootstrap.go - Formatting Update: Added a blank line after error handling in Run function for improved readability.
cli/commands/backend/delete/delete.go - Formatting Update: Added a blank line after error handling in Run function for improved readability.

Possibly related PRs

  • feat: Adding retry for clone errors #3933: The changes in the main PR, which enhance the ErrorsConfig structure and its methods, are related to the modifications in the retrieved PR that introduce an errors block for managing error handling during source cloning, as both involve improvements to error management within the configuration context.

Suggested reviewers

  • levkohimins
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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 to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai 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.

@denis256 denis256 marked this pull request as ready for review March 19, 2025 21:05
@denis256 denis256 requested review from lev-ok and yhakbar as code owners March 19, 2025 21:05
yhakbar
yhakbar previously approved these changes Mar 19, 2025
clone.Retry[i] = retry.Clone()
// Merge combines the current ErrorsConfig with another one, prioritizing the other config
func (c *ErrorsConfig) Merge(other *ErrorsConfig) {
if c == nil || other == nil {
Copy link
Collaborator

Choose a reason for hiding this comment

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

If you merge a config into a nil config, shouldn't you expect that c becomes other?

Copy link
Member Author

Choose a reason for hiding this comment

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

Since changes to the receiver don't affect the caller, initializing c has no outside effect - better to return early if null.

if otherBlock.SleepIntervalSec > 0 {
existingBlock.SleepIntervalSec = otherBlock.SleepIntervalSec
}
} else {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Consider replacing the else with a continue to dodge the nest here.

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)
util/collections.go (1)

228-244: Clarify doc about Go map iteration order
The doc comment implies that the slice preserves an original order from the map. However, Go maps do not guarantee a stable iteration order across runs. Consider updating the comment to reflect that the function simply appends values in the order they are encountered, which is not deterministic.

-// It extracts all values from the map and returns them as a slice while maintaining their original order in the map iteration.
+// It extracts all values from the map and returns them as a slice in the order 
+// encountered during iteration, which is not guaranteed to remain consistent 
+// across runs due to Go's non-deterministic map iteration.
config/errors_block.go (1)

44-52: In-place merge may cause side effects
The Merge method mutates the original ErrorsConfig instead of returning a new merged configuration. If this is intentional, it’s fine. Otherwise, returning a new copy might help avoid unintended modifications.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 89a9808 and 69bd298.

📒 Files selected for processing (2)
  • config/errors_block.go (2 hunks)
  • util/collections.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.go`: Review the Go code for quality and correctness. Make sure that the Go code follows best practices, is performant, and is easy to understand and maintain.

**/*.go: Review the Go code for quality and correctness. Make sure that the Go code follows best practices, is performant, and is easy to understand and maintain.

  • util/collections.go
  • config/errors_block.go
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Pull Request has non-contributor approval
  • GitHub Check: build-and-test
  • GitHub Check: Pull Request has non-contributor approval
🔇 Additional comments (10)
config/errors_block.go (10)

12-13: Struct fields look good
The Retry and Ignore fields are clearly declared, using appropriate struct tags for cty and hcl.


32-42: Ensure coverage for deep clone functionality
This approach correctly deep-clones ErrorsConfig by cloning its constituent slices. Consider verifying in tests by mutating clones to confirm that no unintended references remain.


54-66: Clone logic for RetryBlock
Implementation is straightforward, ensuring a proper deep copy of all fields.


68-80: Clone logic for IgnoreBlock
Method mirrors the RetryBlock logic. Looks correct for deep copying all fields, including the signals map.


82-94: Deep copy of RetryBlock slices
This helper correctly invokes Clone() on each RetryBlock, ensuring no references to the original slice.


96-108: Deep copy of IgnoreBlock slices
Implementation parallels cloneRetryBlocks; no issues spotted.


110-120: Cloning string slices
Simple copy approach using make and copy is correct.


122-132: Cloning signals map
Using maps.Copy is appropriate for a deep copy without referencing the original map.


134-161: Zero-values not overridden
In mergeRetryBlocks, zero values for MaxAttempts and SleepIntervalSec are skipped. Confirm whether ignoring an explicit zero in the other slice is intended or if you need to allow overriding with zero.


163-195: Empty messages not merged
In mergeIgnoreBlocks, you skip assigning an empty message to overwrite an existing one. Verify if this is desired or if you want an empty string to clear an old message.

@denis256 denis256 marked this pull request as draft March 21, 2025 20:06
@denis256 denis256 marked this pull request as ready for review March 28, 2025 09:48
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)
config/errors_block.go (2)

143-158: Consider fixing code style in the mergeRetryBlocks function

The function logic is correct, but there's a minor style issue with branch statement cuddling. According to static analysis hints, branch statements should not be cuddled if the block has more than two lines.

            if otherBlock.SleepIntervalSec > 0 {
                existingBlock.SleepIntervalSec = otherBlock.SleepIntervalSec
            }
+
            continue
        }
        retryMap[otherBlock.Label] = otherBlock
🧰 Tools
🪛 golangci-lint (1.64.8)

155-155: branch statements should not be cuddled if block has more than two lines

(wsl)


157-157: assignments should only be cuddled with other assignments

(wsl)


172-191: Consider using continue instead of else in mergeIgnoreBlocks

For consistency with the mergeRetryBlocks implementation and to reduce nesting, consider using continue instead of else here.

        if existingBlock, found := ignoreMap[otherBlock.Label]; found {
            existingBlock.IgnorableErrors = util.MergeStringSlices(existingBlock.IgnorableErrors, otherBlock.IgnorableErrors)

            if otherBlock.Message != "" {
                existingBlock.Message = otherBlock.Message
            }

            if otherBlock.Signals != nil {
                if existingBlock.Signals == nil {
                    existingBlock.Signals = make(map[string]cty.Value, len(otherBlock.Signals))
                }

                maps.Copy(existingBlock.Signals, otherBlock.Signals)
            }
+           continue
-        } else {
-            ignoreMap[otherBlock.Label] = otherBlock
-        }
+       }
+       ignoreMap[otherBlock.Label] = otherBlock
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 69bd298 and c4c2313.

📒 Files selected for processing (2)
  • config/config.go (0 hunks)
  • config/errors_block.go (2 hunks)
💤 Files with no reviewable changes (1)
  • config/config.go
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.go`: Review the Go code for quality and correctness. Make sure that the Go code follows best practices, is performant, and is easy to understand and maintain.

**/*.go: Review the Go code for quality and correctness. Make sure that the Go code follows best practices, is performant, and is easy to understand and maintain.

  • config/errors_block.go
🧬 Code Definitions (1)
config/errors_block.go (2)
options/options.go (1)
  • ErrorsConfig (654-657)
util/collections.go (2)
  • MergeStringSlices (214-227)
  • MapToSlice (237-244)
🪛 golangci-lint (1.64.8)
config/errors_block.go

155-155: branch statements should not be cuddled if block has more than two lines

(wsl)


157-157: assignments should only be cuddled with other assignments

(wsl)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: unessential
  • GitHub Check: build-and-test
  • GitHub Check: Pull Request has non-contributor approval
🔇 Additional comments (10)
config/errors_block.go (10)

32-41: The Clone method implementation is well structured

Good use of nil checking and the new helper methods for deep copying the Retry and Ignore fields. This ensures a proper deep copy while maintaining nil check safety.


44-52: The Merge method handles nil receivers appropriately

The early return for nil cases is a good practice. Since we're merging configurations, checking that both the receiver and argument are non-nil prevents unexpected behavior.


54-66: The RetryBlock.Clone method is well implemented

The method correctly handles nil receivers and performs a proper deep copy of the RetryableErrors slice using the cloneStringSlice helper function.


68-80: The IgnoreBlock.Clone method is correctly implemented

Good implementation with nil checking and proper deep copying of all fields, particularly the Signals map using the cloneSignalsMap helper.


82-94: The cloneRetryBlocks helper function is well structured

This helper effectively creates a deep copy of a slice of RetryBlock pointers. The nil check at the beginning is appropriate, and the implementation is clear and concise.


96-108: The cloneIgnoreBlocks helper function is well implemented

Similar to cloneRetryBlocks, this function properly handles nil inputs and creates a deep copy of each IgnoreBlock in the slice.


110-120: The cloneStringSlice helper function is efficient

Good use of the built-in copy function to efficiently duplicate the string slice while preserving nil behavior.


122-132: The cloneSignalsMap helper function is correctly implemented

Good use of maps.Copy for efficient copying of the map contents. The nil check provides proper safety for edge cases.


134-161: Good implementation of merging logic for RetryBlocks

The implementation efficiently uses a map for lookups and correctly prioritizes values from the other RetryBlocks while preserving existing values where appropriate. The use of MapToSlice for the final conversion is clean.

🧰 Tools
🪛 golangci-lint (1.64.8)

155-155: branch statements should not be cuddled if block has more than two lines

(wsl)


157-157: assignments should only be cuddled with other assignments

(wsl)


163-195: Good implementation of merging logic for IgnoreBlocks

The merging logic correctly handles all IgnoreBlock fields, with proper handling of nil maps and prioritization of the other configuration. The use of MapToSlice is consistent with the RetryBlocks implementation.

yhakbar
yhakbar previously approved these changes Mar 28, 2025
Copy link
Collaborator

@yhakbar yhakbar left a comment

Choose a reason for hiding this comment

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

Tag me when you address the lint error

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 (1)
util/collections_test.go (1)

277-298: Good test implementation with room for enhancement.

The test function follows good practices with parallel execution and proper edge case handling. However, consider these improvements:

  1. Add a test case for a multi-element map to ensure the function works correctly in that scenario.
  2. Use the assert package that's already imported and used elsewhere in the file for consistency instead of manual error reporting with t.Errorf.
func TestMapToSlice(t *testing.T) {
	t.Parallel()

	t.Run("Empty Map", func(t *testing.T) {
		t.Parallel()
		m := make(map[string]*int)
		result := util.MapToSlice(m)
-		if len(result) != 0 {
-			t.Errorf("Expected empty slice, got %v", result)
-		}
+		assert.Empty(t, result, "Expected empty slice")
	})

	t.Run("Single Element Map", func(t *testing.T) {
		t.Parallel()
		val := 42
		m := map[string]*int{"key1": &val}
		result := util.MapToSlice(m)
-		if len(result) != 1 || result[0] != &val {
-			t.Errorf("Expected slice with one element %v, got %v", &val, result)
-		}
+		assert.Len(t, result, 1, "Expected slice with one element")
+		assert.Equal(t, &val, result[0], "Element in slice should match the map value")
	})

+	t.Run("Multi Element Map", func(t *testing.T) {
+		t.Parallel()
+		val1, val2 := 42, 24
+		m := map[string]*int{"key1": &val1, "key2": &val2}
+		result := util.MapToSlice(m)
+		assert.Len(t, result, 2, "Expected slice with two elements")
+		// Since map iteration order is not guaranteed, we check that both values are present
+		values := []*int{&val1, &val2}
+		assert.Contains(t, values, result[0], "First element should be one of the map values")
+		assert.Contains(t, values, result[1], "Second element should be one of the map values")
+		assert.NotEqual(t, result[0], result[1], "Elements should be different")
+	})
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 914e1c3 and b9eb744.

📒 Files selected for processing (2)
  • config/config.go (0 hunks)
  • util/collections_test.go (1 hunks)
💤 Files with no reviewable changes (1)
  • config/config.go
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.go`: Review the Go code for quality and correctness. Make sure that the Go code follows best practices, is performant, and is easy to understand and maintain.

**/*.go: Review the Go code for quality and correctness. Make sure that the Go code follows best practices, is performant, and is easy to understand and maintain.

  • util/collections_test.go
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build-and-test
  • GitHub Check: Pull Request has non-contributor approval

@denis256 denis256 merged commit 2df2cda into main Mar 28, 2025
8 of 9 checks passed
@denis256 denis256 deleted the errors-block-cleanup branch March 28, 2025 17:43
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