Skip to content

Conversation

@yhakbar
Copy link
Collaborator

@yhakbar yhakbar commented Nov 8, 2025

Description

Fixes #5071

TODOs

Read the Gruntwork contribution guidelines.

  • I authored this code entirely myself
  • I am submitting code based on open source software (e.g. MIT, MPL-2.0, Apache)]
  • I am adding or upgrading a dependency or adapted code and confirm it has a compatible open source license
  • Update the docs.
  • Run the relevant tests successfully, including pre-commit checks.
  • 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

  • Bug Fixes

    • Fixed potential nil pointer issues in configuration file parsing to prevent crashes.
    • Added validation to enforce that required attributes are present in configuration blocks.
    • Improved error handling to collect and report multiple configuration issues simultaneously instead of stopping at the first error.
  • Tests

    • Expanded test coverage for configuration validation, including scenarios with missing required attributes.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 8, 2025

📝 Walkthrough

Walkthrough

Added defensive nil-check in ParseConfig to prevent nil pointer dereference after handleInclude. Added validation requiring if_exists attribute on generate blocks, collecting errors during processing instead of returning immediately to enable comprehensive error reporting.

Changes

Cohort / File(s) Change Summary
Generate Block Validation
config/config.go
Added nil-check after handleInclude and validation logic for generate blocks: requires if_exists attribute and appends errors to errs instead of returning immediately on validation or generation failures.
Test Coverage
config/config_test.go
Added TestParseConfigWithMissingIfExists test function to verify error handling when generate block lacks if_exists attribute, ensuring non-nil TerragruntConfig is returned alongside error.

Sequence Diagram

sequenceDiagram
    participant User
    participant ParseConfig
    participant handleInclude
    participant convertToTerragruntConfig
    participant validateGenerate

    User->>ParseConfig: Parse config
    ParseConfig->>handleInclude: Handle include
    handleInclude-->>ParseConfig: return config or nil
    
    alt Config is nil (NEW)
        ParseConfig-->>User: Return current config + errors
    else Config exists
        ParseConfig->>convertToTerragruntConfig: Convert to terragrunt config
        
        loop For each generate block
            convertToTerragruntConfig->>validateGenerate: Check if_exists attribute (NEW)
            alt if_exists missing
                validateGenerate-->>convertToTerragruntConfig: Append error, continue
            else if_exists present
                validateGenerate-->>convertToTerragruntConfig: Generate value (NEW)
                alt Generation fails (NEW)
                    convertToTerragruntConfig->>convertToTerragruntConfig: Append error, continue
                else Generation succeeds
                    convertToTerragruntConfig->>convertToTerragruntConfig: Process normally
                end
            end
        end
        
        convertToTerragruntConfig-->>ParseConfig: Return config with accumulated errors
        ParseConfig-->>User: Return TerragruntConfig + errors
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

  • Error-handling changes follow an established pattern from prior work (appending to error list rather than early returns)
  • Test is straightforward validation of the new error-collection behavior
  • Changes are localized to error-handling paths with minimal logic density

Possibly related PRs

  • PR #4044: Introduced the best-effort error-accumulation pattern for generate block processing that this change extends with defensive nil-checking and required attribute validation.

Suggested reviewers

  • levkohimins
  • denis256

Pre-merge checks and finishing touches

❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Description check ❓ Inconclusive The PR description follows the template with issue reference #5071, but release notes section is not populated with actual content. Complete the release notes section with a one-line description of changes and note any backward compatibility impacts.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The PR title accurately and concisely describes the main fix: preventing a panic when a generate block is missing the if_exists attribute.
Linked Issues check ✅ Passed The code changes address the core requirement from issue #5071: preventing a panic when a generate block lacks the if_exists attribute, by adding validation and error collection.
Out of Scope Changes check ✅ Passed All changes are scoped to fixing the missing if_exists validation issue; the defensive nil-check and error handling are directly related to the panic prevention objective.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/avoid-panic-on-missing-if_exists

Comment @coderabbitai help to get the list of available commands and usage tips.

@vercel
Copy link

vercel bot commented Nov 8, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
terragrunt-docs Ready Ready Preview Comment Nov 8, 2025 1:06pm

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)
config/config_test.go (1)

1552-1571: Test correctly verifies the fix for missing if_exists attribute.

The test validates that:

  1. An error is returned when if_exists is missing
  2. A non-nil config is returned (best-effort parsing)
  3. The error message mentions the missing attribute

Consider adding a complementary test case for an invalid if_exists value (e.g., if_exists = "invalid_value") to ensure that scenario is also handled gracefully:

func TestParseConfigWithInvalidIfExists(t *testing.T) {
	t.Parallel()

	cfg := `generate "test" {
  path     = "test.tf"
  contents = "foo"
  if_exists = "invalid_value"
}`

	l := createLogger()
	ctx := config.NewParsingContext(t.Context(), l, mockOptionsForTest(t))

	terragruntConfig, err := config.ParseConfigString(ctx, l, config.DefaultTerragruntConfigPath, cfg, nil)
	require.Error(t, err)
	assert.Contains(t, err.Error(), "generate")
	assert.NotNil(t, terragruntConfig)
}
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 480cad8 and de7643f.

📒 Files selected for processing (2)
  • config/config.go (2 hunks)
  • config/config_test.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go

⚙️ CodeRabbit configuration file

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.

Files:

  • config/config_test.go
  • config/config.go
🧬 Code graph analysis (2)
config/config_test.go (2)
config/parsing_context.go (1)
  • NewParsingContext (62-73)
config/config.go (2)
  • ParseConfigString (1217-1230)
  • DefaultTerragruntConfigPath (48-48)
config/config.go (1)
codegen/generate.go (1)
  • GenerateConfigExistsFromString (585-598)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (12)
  • GitHub Check: build_no_proxy / Build (windows/386)
  • GitHub Check: build_no_proxy / Build (darwin/arm64)
  • GitHub Check: build_no_proxy / Build (linux/amd64)
  • GitHub Check: build_no_proxy / Build (linux/arm64)
  • GitHub Check: build / Build (windows/amd64)
  • GitHub Check: build / Build (windows/386)
  • GitHub Check: build / Build (darwin/amd64)
  • GitHub Check: build / Build (linux/amd64)
  • GitHub Check: build / Build (darwin/arm64)
  • GitHub Check: base_tests / Test (macos)
  • GitHub Check: base_tests / Test (ubuntu)
  • GitHub Check: build-and-test
🔇 Additional comments (2)
config/config.go (2)

1742-1751: Good error collection pattern for validation.

The validation correctly enforces the required if_exists attribute and collects all errors before returning. This improves user experience by showing all validation errors at once rather than failing on the first error.

The use of continue instead of immediate return allows processing to continue and collect errors from all generate blocks.


1338-1343: The defensive nil-check is appropriate and necessary; handleInclude legitimately returns nil on merge errors.

The verification shows that handleInclude returns (nil, error) in three error conditions (lines 158, 166, 171 in config/include.go), all related to failures during merge operations. The nil-check at lines 1338-1343 correctly handles this designed behavior: when a merge fails, the function signals failure by returning nil, and the caller appropriately stops processing and returns accumulated errors.

This is proper error handling, not a symptom treatment—the merge failures are being correctly propagated up the call stack.

@yhakbar yhakbar merged commit a930852 into main Nov 10, 2025
120 of 124 checks passed
@yhakbar yhakbar deleted the fix/avoid-panic-on-missing-if_exists branch November 10, 2025 13:46
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.

crash if generate block has no if_exists attribute

4 participants