Skip to content

feat: enhance error messages in atmos validate stacks with file context - #1494

Merged
Andriy Knysh (aknysh) merged 21 commits into
mainfrom
improve-atmos-validate
Sep 23, 2025
Merged

Andriy Knysh (aknysh) merged 21 commits into
mainfrom
improve-atmos-validate

Conversation

@osterman

@osterman Erik Osterman (Cloud Posse) (osterman) commented Sep 22, 2025 •

Copy link
Copy Markdown
Member

Summary

This PR addresses the issue where atmos validate stacks shows cryptic merge errors without any indication of which file contains the problem. Users were seeing duplicate, unformatted error messages with no context about where the configuration conflicts occurred.

image

Problem

When users encountered merge errors (like type mismatches between arrays and strings), they would see:

  1. Duplicate error messages - The same error printed multiple times to stderr
  2. No file context - No indication of which file or import chain caused the issue
  3. Difficult debugging - Impossible to identify the source of conflicts in complex configurations

Example of the problematic output:

cannot override two slices with different type ([]interface {}, string)
cannot override two slices with different type ([]interface {}, string)
cannot override two slices with different type ([]interface {}, string)
...

Solution

This PR implements two key improvements:

1. Fixed Duplicate Error Printing

  • Root Cause: merge.go was printing errors directly to stderr using theme.Colors.Error.Fprintln() before returning them
  • Fix: Removed all direct printing statements (3 locations)
  • Result: Errors now flow through proper logging channels and appear once

2. Added MergeContext for Enhanced Error Messages

  • File Tracking: Shows exactly which file is being processed when an error occurs
  • Import Chain: Displays the complete chain of imports leading to the error
  • Helpful Hints: Provides specific guidance for common merge errors
  • Debug Logging: Logs merge operations and failures at Debug level with full context

Example Output

Before:

cannot override two slices with different type ([]interface {}, string)
cannot override two slices with different type ([]interface {}, string)

After:

Error: cannot override two slices with different type ([]interface {}, string)

  File being processed: stacks/deploy/prod/us-east-1.yaml
  Import chain:
    → stacks/catalog/base.yaml
    → stacks/mixins/region/us-east-1.yaml
    → stacks/deploy/prod/us-east-1.yaml

  Likely cause: A key is defined as an array in one file and as a string in another.
  Debug hint: Check the files above for keys that have different types.
  Common issues:
    - vars defined as both array and string
    - settings with inconsistent types across imports
    - overrides attempting to change field types

Changes Made

  • Created MergeContext struct to track file paths and import chains
  • Added MergeWithContext and ProcessYAMLConfigFileWithContext functions
  • Removed direct stderr printing from merge.go
  • Added debug logging for merge operations
  • Comprehensive test coverage for all changes
  • Full backward compatibility maintained

Testing

  • Unit tests for MergeContext functionality
  • Tests verifying no duplicate error printing
  • Integration tests for validate command
  • Test fixtures demonstrating type mismatch scenarios
  • All existing tests continue to pass

Benefits

  1. Clear Error Location: Users immediately know which file contains the problem
  2. Import Chain Visibility: Shows the complete path of imports leading to the error
  3. No Duplicates: Errors appear once with proper formatting
  4. Actionable Hints: Specific guidance on resolving type mismatches
  5. Debug Support: Debug logging provides additional context when needed
  6. Non-Breaking: Fully backward compatible with existing code

Test Plan

  • Run unit tests: go test ./pkg/merge -v
  • Run integration tests: go test ./internal/exec -run TestValidateStacks
  • Manual testing with type mismatch scenarios
  • Verify no stderr printing occurs
  • Verify debug logging works correctly
  • Ensure backward compatibility

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Context-rich error messages during validation and merges showing the file being processed, import chain, and actionable hints.
  • Bug Fixes
    • Suppressed duplicate stderr printing; errors are now returned and wrapped with contextual information instead of printed.
  • Documentation
    • Added user guide documenting enhanced error formatting, debugging tips, examples, and backward-compatibility notes.
  • Tests
    • Expanded test suite and fixtures validating context-aware error formatting, duplicate-suppression, import chains, and type-mismatch scenarios.

This commit addresses the issue where 'atmos validate stacks' shows cryptic
merge errors without any indication of which file contains the problem.

## what
- Add MergeContext to track file paths and import chains during merge operations
- Remove duplicate error printing from merge.go (was printing to stderr directly)
- Add proper debug logging for merge operations and failures
- Provide clear, actionable error messages with file context

## why
Users were seeing duplicate, unformatted error messages like:
'cannot override two slices with different type ([]interface {}, string)'
with no indication of which files contained the conflicting configurations.

This made debugging complex stack configurations extremely difficult,
especially with deep import chains.

## changes
- Created MergeContext struct to track current file and import chain
- Added MergeWithContext and ProcessYAMLConfigFileWithContext functions
- Removed direct stderr printing from merge.go (3 locations)
- Added debug logging for merge operations with context
- Enhanced error messages to show:
  - File being processed when error occurs
  - Complete import chain leading to the error
  - Helpful hints about likely causes and common issues
- Added comprehensive test coverage for all changes
- Maintains full backward compatibility

## example
Before:
```
cannot override two slices with different type ([]interface {}, string)
cannot override two slices with different type ([]interface {}, string)
```

After:
```
Error: cannot override two slices with different type ([]interface {}, string)

  File being processed: stacks/deploy/prod/us-east-1.yaml
  Import chain:
    → stacks/catalog/base.yaml
    → stacks/mixins/region/us-east-1.yaml
    → stacks/deploy/prod/us-east-1.yaml

  Likely cause: A key is defined as an array in one file and as a string in another.
  Debug hint: Check the files above for keys that have different types.
```

🤖 Generated with Claude Code

Co-Authored-By: Claude <[email protected]>
@coderabbitai

coderabbitai Bot commented Sep 22, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Threads a new MergeContext through merge and YAML processing to attach file/import-chain context to merge errors, replaces direct stderr prints with wrapped errors, introduces MergeWithContext APIs, adds tests/docs, and switches stack validation to a two‑pass flow to collect imports before validating stacks.

Changes

Cohort / File(s) Summary
Docs: Enhanced Errors Demo
demo_enhanced_errors.md
New documentation describing MergeContext, enhanced error formatting, implementation notes, examples, debugging hints, and backward-compatible integration.
Stack processing (exec)
internal/exec/stack_processor_utils.go, internal/exec/validate_stacks.go, internal/exec/validate_stacks_test.go
Add ProcessYAMLConfigFileWithContext; initialize/propagate MergeContext through YAML processing and imports; legacy ProcessYAMLConfigFile delegates to context variant; adopt two‑pass validation (collect imports, then validate top-level files); update tests for context-aware error formatting.
Merge core & context
pkg/merge/merge.go, pkg/merge/merge_context.go, pkg/merge/merge_with_context_test.go, pkg/merge/merge_context_test.go, pkg/merge/merge_context_demo_test.go, pkg/merge/merge_no_duplicate_errors_test.go
Add MergeContext type and helpers (NewMergeContext, WithFile, Clone, FormatError, getters); add MergeWithContext and MergeWithOptionsAndContext; annotate/format merge errors via context instead of printing to stderr; add comprehensive tests covering formatting, duplicate-error suppression, and merge strategies.
Errors sentinel
errors/errors.go
Add exported sentinel ErrInvalidStackManifest.
Test fixtures: validate-type-mismatch
tests/test-cases/validate-type-mismatch/...
Add atmos.yaml and many stack YAML fixtures and mixins (e.g., stacks/base.yaml, override.yaml, test-environment.yaml, complex-import-chain.yaml, deep-merge-test.yaml, demo-error.yaml, config1.yaml, config2.yaml, shared/network.yaml, shared/databases.yaml, mixins, examples) to exercise type-mismatch and import-chain scenarios.
Small edits
internal/exec/terraform_plan_diff_formatting.go, internal/exec/version.go
Minor formatting/comment tweaks with no behavior changes.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant CLI as CLI
  participant Exec as Stack Processor
  participant Merge as pkg/merge
  participant Ctx as MergeContext

  CLI->>Exec: ValidateStacks()
  Note over Exec: Pass 1 — process files (ignoreMissingFiles=true)\ncollect imports into importsConfig
  CLI->>Exec: ValidateStacks() (Pass 2)
  Exec->>Exec: skip files marked as imports
  Exec->>Exec: for each top-level file: ctx := NewMergeContext().WithFile(file)
  Exec->>Merge: MergeWithContext(atmosCfg, inputs, ctx)
  Merge->>Merge: MergeWithOptionsAndContext(...)
  alt Merge succeeds
    Merge-->>Exec: merged map
    Exec-->>CLI: validation success
  else Merge error
    Merge->>Ctx: ctx.FormatError(err, hints)
    Merge-->>Exec: formatted/wrapped error (returned)
    Exec-->>CLI: error returned (not printed)
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~30 minutes

Possibly related PRs

Suggested reviewers

  • osterman
  • aknysh

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title is a concise, single-sentence summary that clearly highlights the main change: improving error messages for "atmos validate stacks" by adding file context. It is directly related to the changes in the PR (MergeContext, context-aware merge/processing, and reduced duplicate stderr prints) and uses a conventional "feat:" prefix. The phrasing is specific and readable, making it suitable for changelogs and history scanning.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch improve-atmos-validate

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@github-actions github-actions Bot added the size/xl Extra large size PR label Sep 22, 2025
@mergify

mergify Bot commented Sep 22, 2025

Copy link
Copy Markdown
Contributor

Warning

This PR exceeds the recommended limit of 1,000 lines.

Large PRs are difficult to review and may be rejected due to their size.

Please verify that this PR does not address multiple issues.
Consider refactoring it into smaller, more focused PRs to facilitate a smoother review process.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
pkg/merge/merge_no_duplicate_errors_test.go (1)

1-225: Remove direct stderr write in pkg/logger/logger.go:113

theme.Colors.Error.Fprintln(color.Error, ...) at pkg/logger/logger.go:113 prints directly to stderr — remove/replace it by returning/wrapping the error or routing output through the central CLI/logger layer so callers control presentation.

🧹 Nitpick comments (23)
tests/test-cases/validate-type-mismatch/stacks/base.yaml (1)

19-19: Add trailing newline to satisfy linters.

EOF newline is missing and flagged by yamllint. Safe to add; content stays identical.

Apply this diff:

-          Purpose: "testing"
+          Purpose: "testing"
+
tests/test-cases/validate-type-mismatch/atmos.yaml (1)

24-24: Add trailing newline to satisfy linters.

EOF newline is missing; keeps CI noise down.

Apply this diff:

-    manifest: ""
+    manifest: ""
+
pkg/merge/merge.go (3)

65-69: Prefer logging the raw error object.

Use the error value, not err.Error(), for structured logs.

Apply this diff:

-			log.Debug("Merge operation failed", "error", err.Error())
+			log.Debug("Merge operation failed", "error", err)

173-176: Tiny lint: end sentence with a period.

Godot linter requires sentence-ending punctuation.

Apply this diff:

-	// Log merge context if available (only in trace/debug mode to avoid noise)
+	// Log merge context if available (only in trace/debug mode to avoid noise).

178-193: Consider single-site formatting of context to avoid double-logs.

You now log once in MergeWithOptions and once here on failure, which can read as duplicates at Debug. Optional: only log in the context-aware wrapper.

internal/exec/stack_processor_utils.go (1)

203-206: Doc comment punctuation.

End the summary sentence with a period to satisfy godot.

Apply this diff:

-// ProcessYAMLConfigFileWithContext takes a path to a YAML stack manifest,
+// ProcessYAMLConfigFileWithContext takes a path to a YAML stack manifest.
pkg/merge/merge_context.go (2)

137-150: Comment punctuation nit.

End the line with a period for godot.

Apply this diff:

-// HasFile checks if a file is already in the import chain (to detect circular imports).
+// HasFile checks if a file is already in the import chain (to detect circular imports).

(No code change needed if your linter accepts the existing form; otherwise append a period explicitly.)


120-127: Optional: clearer chain formatting function name.

GetImportChainString could be ImportChainString(); not blocking.

pkg/merge/merge_no_duplicate_errors_test.go (5)

17-29: Avoid global os.Stderr mutation leaks; add a helper with t.Cleanup.

Repeated pipe/setup/restore logic risks FD leaks and is brittle if a test fails early. Centralize capture with t.Cleanup and close both ends to avoid goroutine leaks.

Add a small helper in this file and use it across tests:

// place near top of file
func captureStderr(t *testing.T) (restore func() string) {
	t.Helper()
	old := os.Stderr
	r, w, _ := os.Pipe()
	os.Stderr = w

	var buf bytes.Buffer
	done := make(chan struct{})
	go func() {
		_, _ = io.Copy(&buf, r)
		close(done)
	}()

	return func() string {
		_ = w.Close()
		os.Stderr = old
		_ = r.Close()
		<-done
		return buf.String()
	}
}

Example usage in this test:

- oldStderr := os.Stderr
- r, w, _ := os.Pipe()
- os.Stderr = w
+ restore := captureStderr(t)
...
- w.Close()
- os.Stderr = oldStderr
- stderrOutput := <-stderrChan
+ stderrOutput := restore()

83-109: DRY the stderr capture in all tests.

Same capture/restore pattern appears here; switch to the shared helper for consistency and safety.


111-151: Context-aware error path looks good; just reuse the stderr helper.

Behavior is correct; prefer the helper for capture/restore.


156-207: Multiple-merge loop is fine; prefer helper and close r/w reliably.

No functional issues; adopt the helper to avoid subtle leaks and simplify.


14-16: Fix comment periods to satisfy godot linter.

Many // comments lack trailing periods; golangci-lint will fail.

Example:

-// TestNoDuplicateErrorPrinting verifies that errors are not printed directly to stderr
-// This was the issue where merge.go was printing errors before returning them
+// TestNoDuplicateErrorPrinting verifies that errors are not printed directly to stderr.
+// This was the issue where merge.go was printing errors before returning them.

Also applies to: 30-33, 59-61, 107-109, 153-155, 219-224

tests/test-cases/validate-type-mismatch/stacks/override.yaml (1)

1-12: Add trailing newline (yamllint).

File lacks a newline at EOF; add one to satisfy linters.

-        additional_setting: "some value"
+        additional_setting: "some value"
+
tests/test-cases/validate-type-mismatch/stacks/test-environment.yaml (1)

1-14: Add trailing newline (yamllint).

Same EOF newline nit as other fixture.

-        environment: "test-env"
+        environment: "test-env"
+
pkg/merge/merge_with_context_test.go (2)

120-155: Global logger mutation: avoid parallelization; assertions on logs optional.

You correctly restore the default logger. Consider noting that this test must not run with t.Parallel, or add a brief comment.


15-18: Fix comment periods to pass godot.

End // comments with periods.

Also applies to: 63-67, 71-76, 99-105, 120-131, 141-155

pkg/merge/merge_context_demo_test.go (3)

24-30: Prefer t.Logf over fmt.Printf in tests.

Avoid noisy stdout in unit tests; use testing logger.

-	fmt.Printf("\n=== Enhanced Error Message ===\n%s\n=== End of Error Message ===\n", enhancedError)
+	t.Logf("\n=== Enhanced Error Message ===\n%s\n=== End of Error Message ===", enhancedError)

53-56: Same: replace fmt.Printf with t.Logf.

-	fmt.Printf("\n=== Complex Scenario Error ===\n%s\n=== End of Error ===\n", enhancedError)
+	t.Logf("\n=== Complex Scenario Error ===\n%s\n=== End of Error ===", enhancedError)

9-11: Add trailing periods to comments.

Aligns with linter requirements.

Also applies to: 33-34

demo_enhanced_errors.md (1)

9-14: Add fenced code languages (markdownlint MD040).

Specify a language for code fences to satisfy markdownlint. Use "text" for plain output.

-```
+```text
 cannot override two slices with different type ([]interface {}, string)
 cannot override two slices with different type ([]interface {}, string)
 cannot override two slices with different type ([]interface {}, string)
 ...
-```
+```

-```
+```text
 cannot override two slices with different type ([]interface {}, string)
-```
+```

-```
+```text
 cannot override two slices with different type ([]interface {}, string)

   File being processed: stacks/deploy/prod/us-east-1.yaml
   Import chain:
     → stacks/orgs/acme/_defaults.yaml
       → stacks/catalog/vpc/defaults.yaml
       → stacks/catalog/vpc/base.yaml
       → stacks/mixins/region/us-east-1.yaml
       → stacks/mixins/account/prod.yaml
       → stacks/deploy/prod/us-east-1.yaml

   Likely cause: A key is defined as an array in one file and as a string in another.
   Debug hint: Check the files above for keys that have different types.
   Common issues:
     - vars defined as both array and string
     - settings with inconsistent types across imports
     - overrides attempting to change field types
-```
+```

Also applies to: 25-28, 30-48

internal/exec/validate_stacks_test.go (1)

78-134: Comments need periods; minor polish.

Several // comments lack periods; fix to satisfy linter.

Also applies to: 135-184

pkg/merge/merge_context_test.go (1)

65-109: Comment periods and message text consistency.

  • End comments with periods to satisfy godot.
  • Keep expected substrings generic (you already use Contains) to avoid brittleness across mergo versions.

Also applies to: 129-145, 147-159, 269-281

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 3e2ed8a and 942d91b.

📒 Files selected for processing (13)
  • demo_enhanced_errors.md (1 hunks)
  • internal/exec/stack_processor_utils.go (7 hunks)
  • internal/exec/validate_stacks_test.go (1 hunks)
  • pkg/merge/merge.go (3 hunks)
  • pkg/merge/merge_context.go (1 hunks)
  • pkg/merge/merge_context_demo_test.go (1 hunks)
  • pkg/merge/merge_context_test.go (1 hunks)
  • pkg/merge/merge_no_duplicate_errors_test.go (1 hunks)
  • pkg/merge/merge_with_context_test.go (1 hunks)
  • tests/test-cases/validate-type-mismatch/atmos.yaml (1 hunks)
  • tests/test-cases/validate-type-mismatch/stacks/base.yaml (1 hunks)
  • tests/test-cases/validate-type-mismatch/stacks/override.yaml (1 hunks)
  • tests/test-cases/validate-type-mismatch/stacks/test-environment.yaml (1 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
tests/test-cases/**

📄 CodeRabbit inference engine (CLAUDE.md)

Never modify golden snapshot fixtures under tests/test-cases/ unless explicitly instructed.

Files:

  • tests/test-cases/validate-type-mismatch/stacks/override.yaml
  • tests/test-cases/validate-type-mismatch/atmos.yaml
  • tests/test-cases/validate-type-mismatch/stacks/base.yaml
  • tests/test-cases/validate-type-mismatch/stacks/test-environment.yaml
**/*.{yaml,yml}

📄 CodeRabbit inference engine (CLAUDE.md)

YAML configs should support Go templating using provided template functions.

Files:

  • tests/test-cases/validate-type-mismatch/stacks/override.yaml
  • tests/test-cases/validate-type-mismatch/atmos.yaml
  • tests/test-cases/validate-type-mismatch/stacks/base.yaml
  • tests/test-cases/validate-type-mismatch/stacks/test-environment.yaml
**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*.go: Use Viper for managing configuration, environment variables, and flags
Use interfaces for external dependencies to facilitate mocking
All code must pass golangci-lint checks
Follow Go's error handling idioms
Use meaningful error messages
Wrap errors with context using fmt.Errorf("context: %w", err)
Consider using a custom error type for domain-specific errors
Follow standard Go coding style
Use gofmt and goimports to format code
Prefer short, descriptive variable names
Use snake_case for environment variables
Document all exported functions, types, and methods
Document complex logic with inline comments
Follow Go's documentation conventions
Use Viper for configuration management
Support configuration via files, environment variables, and flags
Follow the precedence order: flags > environment variables > config file > defaults

**/*.go: All comments in Go code must end with periods (enforced by golangci-lint godot).
Wrap all returned errors using static errors from the errors package; never return dynamic errors directly.
Always bind environment variables with viper.BindEnv() and provide ATMOS_ alternatives for each external var.
Separate structured logging from UI output: use stderr for prompts/errors to user; stdout only for data; never use logging for UI.
Most text UI must go to stderr; only data/results to stdout. Prefer utils.PrintfMessageToTUI for UI messages.
For non-standard execution paths, capture telemetry with telemetry.CaptureCmd or telemetry.CaptureCmdString and never capture user data.
Ensure cross-platform compatibility: prefer SDKs to external binaries, use filepath/os/runtime for portability, and add build constraints when needed.

Files:

  • pkg/merge/merge_context_demo_test.go
  • pkg/merge/merge.go
  • pkg/merge/merge_context.go
  • internal/exec/stack_processor_utils.go
  • pkg/merge/merge_with_context_test.go
  • pkg/merge/merge_context_test.go
  • internal/exec/validate_stacks_test.go
  • pkg/merge/merge_no_duplicate_errors_test.go
**/*_test.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*_test.go: Every new feature must include comprehensive unit tests
Test both happy paths and error conditions
Use table-driven tests for testing multiple scenarios
Include integration tests for command flows
Test CLI end-to-end when possible
Use test fixtures for complex inputs
Consider using testify/mock for creating mock implementations

**/*_test.go: Always use t.Skipf() with a reason for skipped tests; never use t.Skip() or reasonless t.Skipf().
Test files must mirror implementation structure and naming (e.g., aws_ssm_store_test.go).
Use table-driven unit tests and mock interfaces for external dependencies; target >80% coverage.

Files:

  • pkg/merge/merge_context_demo_test.go
  • pkg/merge/merge_with_context_test.go
  • pkg/merge/merge_context_test.go
  • internal/exec/validate_stacks_test.go
  • pkg/merge/merge_no_duplicate_errors_test.go
pkg/**/*_test.go

📄 CodeRabbit inference engine (CLAUDE.md)

Unit tests reside under pkg/ alongside implementations.

Files:

  • pkg/merge/merge_context_demo_test.go
  • pkg/merge/merge_with_context_test.go
  • pkg/merge/merge_context_test.go
  • pkg/merge/merge_no_duplicate_errors_test.go
internal/exec/stack_processor_utils.go

📄 CodeRabbit inference engine (CLAUDE.md)

internal/exec/stack_processor_utils.go: Place core stack processing utilities here and reuse them.
Stack processing utilities should reside here; test multiple inheritance scenarios.

Files:

  • internal/exec/stack_processor_utils.go
🧠 Learnings (26)
📚 Learning: 2025-07-01T02:22:25.901Z
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*_test.go : Test both happy paths and error conditions

Applied to files:

  • pkg/merge/merge_context_demo_test.go
  • pkg/merge/merge_with_context_test.go
  • internal/exec/validate_stacks_test.go
  • pkg/merge/merge_no_duplicate_errors_test.go
📚 Learning: 2025-07-01T02:22:25.901Z
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*.go : Wrap errors with context using `fmt.Errorf("context: %w", err)`

Applied to files:

  • pkg/merge/merge_context_demo_test.go
📚 Learning: 2025-06-02T14:12:02.710Z
Learnt from: milldr
PR: cloudposse/atmos#1229
File: internal/exec/workflow_test.go:0-0
Timestamp: 2025-06-02T14:12:02.710Z
Learning: In the atmos codebase, workflow error handling was refactored to use `PrintErrorMarkdown` followed by returning specific error variables (like `ErrWorkflowNoSteps`, `ErrInvalidFromStep`, `ErrInvalidWorkflowStepType`, `ErrWorkflowStepFailed`) instead of `PrintErrorMarkdownAndExit`. This pattern allows proper error testing without the function terminating the process with `os.Exit`, enabling unit tests to assert on error conditions while maintaining excellent user-facing error formatting.

Applied to files:

  • demo_enhanced_errors.md
  • pkg/merge/merge_no_duplicate_errors_test.go
📚 Learning: 2025-06-02T14:12:02.710Z
Learnt from: milldr
PR: cloudposse/atmos#1229
File: internal/exec/workflow_test.go:0-0
Timestamp: 2025-06-02T14:12:02.710Z
Learning: In the atmos codebase, workflow error handling was refactored to use `PrintErrorMarkdown` followed by returning the error instead of `PrintErrorMarkdownAndExit`. This pattern allows proper error testing without the function terminating the process with `os.Exit`, enabling unit tests to assert on error conditions.

Applied to files:

  • demo_enhanced_errors.md
  • pkg/merge/merge_no_duplicate_errors_test.go
📚 Learning: 2025-09-13T18:06:07.674Z
Learnt from: samtholiya
PR: cloudposse/atmos#1466
File: toolchain/list.go:39-42
Timestamp: 2025-09-13T18:06:07.674Z
Learning: In the cloudposse/atmos repository, for UI messages in the toolchain package, use utils.PrintfMessageToTUI instead of log.Error or fmt.Fprintln(os.Stderr, ...). Import pkg/utils with alias "u" to follow the established pattern.

Applied to files:

  • pkg/merge/merge.go
📚 Learning: 2025-09-07T15:13:17.831Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-07T15:13:17.831Z
Learning: Applies to pkg/ui/theme/colors.go : Use theme.Colors constants (e.g., ColorGreen, ColorCyan, ColorRed, ColorSelectedItem, ColorBorder) for UI colors.

Applied to files:

  • pkg/merge/merge.go
📚 Learning: 2025-07-05T20:59:02.914Z
Learnt from: aknysh
PR: cloudposse/atmos#1363
File: internal/exec/template_utils.go:18-18
Timestamp: 2025-07-05T20:59:02.914Z
Learning: In the Atmos project, gomplate v4 is imported with a blank import (`_ "github.com/hairyhenderson/gomplate/v4"`) alongside v3 imports to resolve AWS SDK version conflicts. V3 uses older AWS SDK versions that conflict with newer AWS modules used by Atmos. A full migration to v4 requires extensive refactoring due to API changes and should be handled in a separate PR.

Applied to files:

  • pkg/merge/merge.go
📚 Learning: 2024-11-25T17:17:15.703Z
Learnt from: RoseSecurity
PR: cloudposse/atmos#797
File: pkg/list/atmos.yaml:213-214
Timestamp: 2024-11-25T17:17:15.703Z
Learning: The file `pkg/list/atmos.yaml` is primarily intended for testing purposes.

Applied to files:

  • tests/test-cases/validate-type-mismatch/atmos.yaml
📚 Learning: 2025-09-07T15:13:17.831Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-07T15:13:17.831Z
Learning: Applies to pkg/datafetcher/schema/stacks/stack-config/1.0.json : Update this schema when adding Atmos configuration options.

Applied to files:

  • tests/test-cases/validate-type-mismatch/atmos.yaml
📚 Learning: 2025-03-18T12:26:25.329Z
Learnt from: Listener430
PR: cloudposse/atmos#1149
File: tests/snapshots/TestCLICommands_atmos_vendor_pull_ssh.stderr.golden:7-7
Timestamp: 2025-03-18T12:26:25.329Z
Learning: In the Atmos project, typos or inconsistencies in test snapshot files (such as "terrafrom" instead of "terraform") may be intentional as they capture the exact output of commands and should not be flagged as issues requiring correction.

Applied to files:

  • tests/test-cases/validate-type-mismatch/atmos.yaml
📚 Learning: 2025-09-07T15:13:17.831Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-07T15:13:17.831Z
Learning: Applies to pkg/datafetcher/schema/atmos/manifest/1.0.json : Update this schema when adding Atmos configuration options.

Applied to files:

  • tests/test-cases/validate-type-mismatch/atmos.yaml
📚 Learning: 2025-09-07T15:13:17.831Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-07T15:13:17.831Z
Learning: Applies to pkg/datafetcher/schema/config/global/1.0.json : Update this schema when adding Atmos configuration options.

Applied to files:

  • tests/test-cases/validate-type-mismatch/atmos.yaml
📚 Learning: 2025-09-07T15:13:17.831Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-07T15:13:17.831Z
Learning: Applies to pkg/datafetcher/schema/vendor/package/1.0.json : Update this schema when adding Atmos configuration options.

Applied to files:

  • tests/test-cases/validate-type-mismatch/atmos.yaml
📚 Learning: 2024-12-12T15:17:45.245Z
Learnt from: osterman
PR: cloudposse/atmos#808
File: examples/demo-atmos.d/atmos.d/tools/helmfile.yml:10-10
Timestamp: 2024-12-12T15:17:45.245Z
Learning: In `examples/demo-atmos.d/atmos.d/tools/helmfile.yml`, when suggesting changes to `kubeconfig_path`, ensure that the values use valid Go template syntax.

Applied to files:

  • tests/test-cases/validate-type-mismatch/atmos.yaml
📚 Learning: 2025-01-25T15:21:40.413Z
Learnt from: osterman
PR: cloudposse/atmos#808
File: examples/demo-atmos-cli-imports/atmos.yaml:8-8
Timestamp: 2025-01-25T15:21:40.413Z
Learning: In Atmos, when a directory is specified for configuration loading (e.g., in the `import` section of atmos.yaml), all files within that directory should be treated as Atmos configurations. Do not suggest restricting file extensions in directory-based glob patterns.

Applied to files:

  • tests/test-cases/validate-type-mismatch/atmos.yaml
📚 Learning: 2025-09-10T21:17:55.273Z
Learnt from: samtholiya
PR: cloudposse/atmos#1466
File: toolchain/http_client_test.go:3-10
Timestamp: 2025-09-10T21:17:55.273Z
Learning: In the cloudposse/atmos repository, imports should never be changed as per samtholiya's coding guidelines.

Applied to files:

  • tests/test-cases/validate-type-mismatch/atmos.yaml
📚 Learning: 2025-01-08T19:01:32.938Z
Learnt from: osterman
PR: cloudposse/atmos#899
File: examples/tests/test-vendor/test-components/main.tf:1-7
Timestamp: 2025-01-08T19:01:32.938Z
Learning: In the examples/tests directory of the atmos project, code examples are intentionally kept minimal and simple to facilitate understanding. Avoid suggesting additional complexity or validations that might make the examples harder to follow.

Applied to files:

  • tests/test-cases/validate-type-mismatch/atmos.yaml
📚 Learning: 2025-09-07T15:13:17.831Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-07T15:13:17.831Z
Learning: Applies to pkg/utils/yaml_utils.go : Prefer existing YAML processing utilities in pkg/utils/yaml_utils.go before adding new ones.

Applied to files:

  • internal/exec/stack_processor_utils.go
📚 Learning: 2024-11-19T23:00:45.899Z
Learnt from: osterman
PR: cloudposse/atmos#795
File: internal/exec/stack_processor_utils.go:378-386
Timestamp: 2024-11-19T23:00:45.899Z
Learning: In the `ProcessYAMLConfigFile` function within `internal/exec/stack_processor_utils.go`, directory traversal in stack imports is acceptable and should not be restricted.

Applied to files:

  • internal/exec/stack_processor_utils.go
📚 Learning: 2024-12-07T16:16:13.038Z
Learnt from: Listener430
PR: cloudposse/atmos#825
File: internal/exec/helmfile_generate_varfile.go:28-31
Timestamp: 2024-12-07T16:16:13.038Z
Learning: In `internal/exec/helmfile_generate_varfile.go`, the `--help` command (`./atmos helmfile generate varfile --help`) works correctly without requiring stack configurations, and the only change needed was to make `ProcessCommandLineArgs` exportable by capitalizing its name.

Applied to files:

  • internal/exec/stack_processor_utils.go
📚 Learning: 2025-07-01T02:22:25.901Z
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*_test.go : Every new feature must include comprehensive unit tests

Applied to files:

  • pkg/merge/merge_with_context_test.go
📚 Learning: 2025-09-07T15:13:17.831Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-07T15:13:17.831Z
Learning: Applies to pkg/**/*_test.go : Unit tests reside under pkg/ alongside implementations.

Applied to files:

  • pkg/merge/merge_with_context_test.go
📚 Learning: 2024-10-20T00:41:57.135Z
Learnt from: haitham911
PR: cloudposse/atmos#731
File: internal/exec/validate_stacks.go:93-98
Timestamp: 2024-10-20T00:41:57.135Z
Learning: When downloading schema files in `internal/exec/validate_stacks.go`, use a consistent temporary file name to overwrite the file each time and avoid creating multiple temporary files.

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2025-09-07T15:13:17.831Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-07T15:13:17.831Z
Learning: Applies to internal/exec/stack_processor_utils.go : Stack processing utilities should reside here; test multiple inheritance scenarios.

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2024-11-13T21:37:07.852Z
Learnt from: Cerebrovinny
PR: cloudposse/atmos#764
File: internal/exec/describe_stacks.go:289-295
Timestamp: 2024-11-13T21:37:07.852Z
Learning: In the `internal/exec/describe_stacks.go` file of the `atmos` project written in Go, avoid extracting the stack name handling logic into a helper function within the `ExecuteDescribeStacks` method, even if the logic appears duplicated.

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2025-01-09T22:27:25.538Z
Learnt from: samtholiya
PR: cloudposse/atmos#914
File: cmd/validate_stacks.go:20-23
Timestamp: 2025-01-09T22:27:25.538Z
Learning: The validate commands in Atmos can have different help handling implementations. Specifically, validate_component.go and validate_stacks.go are designed to handle help requests differently, with validate_stacks.go including positional argument checks while validate_component.go does not.

Applied to files:

  • internal/exec/validate_stacks_test.go
🧬 Code graph analysis (7)
pkg/merge/merge_context_demo_test.go (1)
pkg/merge/merge_context.go (1)
  • NewMergeContext (23-27)
pkg/merge/merge.go (3)
pkg/schema/schema.go (2)
  • AtmosConfiguration (25-60)
  • Settings (834-838)
pkg/merge/merge_context.go (1)
  • MergeContext (10-20)
errors/errors.go (3)
  • ErrMerge (81-81)
  • ErrAtmosConfigIsNil (79-79)
  • ErrInvalidListMergeStrategy (80-80)
internal/exec/stack_processor_utils.go (4)
pkg/schema/schema.go (1)
  • AtmosConfiguration (25-60)
pkg/merge/merge_context.go (2)
  • MergeContext (10-20)
  • NewMergeContext (23-27)
pkg/utils/file_utils.go (1)
  • TrimBasePathFromPath (82-86)
pkg/merge/merge.go (1)
  • MergeWithContext (115-164)
pkg/merge/merge_with_context_test.go (3)
pkg/schema/schema.go (3)
  • AtmosConfiguration (25-60)
  • Settings (834-838)
  • AtmosSettings (226-246)
pkg/merge/merge_context.go (1)
  • NewMergeContext (23-27)
pkg/merge/merge.go (1)
  • MergeWithContext (115-164)
pkg/merge/merge_context_test.go (2)
pkg/merge/merge_context.go (2)
  • NewMergeContext (23-27)
  • MergeContext (10-20)
cmd/cmd_utils.go (1)
  • Contains (762-769)
internal/exec/validate_stacks_test.go (3)
pkg/schema/schema.go (7)
  • AtmosConfiguration (25-60)
  • Stacks (352-358)
  • Logs (365-368)
  • Components (346-350)
  • Terraform (306-318)
  • Settings (834-838)
  • AtmosSettings (226-246)
internal/exec/validate_stacks.go (1)
  • ValidateStacks (64-202)
internal/exec/stack_processor_utils.go (1)
  • ProcessYAMLConfigFile (158-201)
pkg/merge/merge_no_duplicate_errors_test.go (3)
pkg/schema/schema.go (3)
  • AtmosConfiguration (25-60)
  • Settings (834-838)
  • AtmosSettings (226-246)
pkg/merge/merge.go (2)
  • Merge (76-112)
  • MergeWithContext (115-164)
pkg/merge/merge_context.go (1)
  • NewMergeContext (23-27)
🪛 YAMLlint (1.37.1)
tests/test-cases/validate-type-mismatch/stacks/override.yaml

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

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

tests/test-cases/validate-type-mismatch/atmos.yaml

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

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

tests/test-cases/validate-type-mismatch/stacks/base.yaml

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

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

tests/test-cases/validate-type-mismatch/stacks/test-environment.yaml

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

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

🪛 markdownlint-cli2 (0.18.1)
demo_enhanced_errors.md

9-9: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


25-25: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


30-30: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

⏰ 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). (6)
  • GitHub Check: Build (macos-latest, macos)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Build (ubuntu-latest, linux)
  • GitHub Check: Analyze (go)
  • GitHub Check: Lint (golangci)
  • GitHub Check: Summary
🔇 Additional comments (12)
internal/exec/stack_processor_utils.go (5)

183-201: Good BC layer: delegating non-context API to the context-aware one.

Keeps signature stable while enabling richer errors. Nice.


235-241: Context chaining looks right.

Creating/advancing the context per file via WithFile(relativeFilePath) preserves the import chain without leaking across siblings. Solid.


378-391: Correctly switching to context-aware merge.

This ensures override failures carry file/import context. Good change.


503-519: Propagating the same context through recursive imports is essential.

This will accumulate the import chain as intended. Looks good.


611-615: Nice: rely on merge to format errors; avoid ad-hoc message building here.

This prevents duplication and centralizes formatting.

pkg/merge/merge_no_duplicate_errors_test.go (1)

42-57: LGTM: verifies error is returned and not printed.

Asserting ErrInvalidListMergeStrategy and empty stderr matches the new behavior.

tests/test-cases/validate-type-mismatch/stacks/override.yaml (1)

1-12: Fixture content is appropriate for type-mismatch tests.

Intentional string override for subnets to trigger merge/type diagnostics looks good.

tests/test-cases/validate-type-mismatch/stacks/test-environment.yaml (1)

1-14: Imports and vars arrangement looks correct for the scenario.

Imports resolve to base.yaml and override.yaml in the same folder; OK.

pkg/merge/merge_with_context_test.go (1)

14-97: Good table-driven coverage of context-enhanced errors.

Scenarios and flexible assertions around mergo behavior are sensible.

internal/exec/validate_stacks_test.go (2)

14-41: Solid harness; debug logging helpful.

Setup mirrors production paths and enables debug for richer traces.


47-76: Assertion strategy is pragmatic given mergo variance.

Flexible checks for context markers are fine; consider expanding expected parts when context is guaranteed.

Would you confirm ValidateStacks/ProcessYAMLConfigFile ultimately call ProcessYAMLConfigFileWithContext with a non-nil MergeContext so file/import context is always present?

pkg/merge/merge_context_test.go (1)

11-17: Great coverage of MergeContext API and FormatError.

API surface, nil-receiver behavior, and real-world scenarios are well tested.

Also applies to: 19-41, 42-63, 65-178, 180-197, 199-217, 219-238, 240-253, 254-282

Comment thread pkg/merge/merge_context.go Resolved
Comment thread pkg/merge/merge.go Resolved
@osterman Erik Osterman (Cloud Posse) (osterman) added the minor New features that do not break anything label Sep 22, 2025
coderabbitai[bot]
coderabbitai Bot previously approved these changes Sep 22, 2025
- Fix FormatError to properly wrap errors with %w instead of converting to string
- Remove redundant error formatting in MergeWithContext
- Use t.Skipf instead of t.Skip with proper reason

These changes ensure proper error type preservation for programmatic handling
and follow Go testing conventions.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (5)
pkg/merge/merge_context.go (2)

70-90: Small allocation nit: avoid fmt.Sprintf inside WriteString.

Use chained WriteString calls for slightly less overhead.

- sb.WriteString(fmt.Sprintf("File being processed: %s", mc.CurrentFile))
+ sb.WriteString("File being processed: ")
+ sb.WriteString(mc.CurrentFile)

- sb.WriteString(fmt.Sprintf("%s%s", prefix, file))
+ sb.WriteString(prefix)
+ sb.WriteString(file)

Also applies to: 93-103


8-9: Fix godot lints: ensure all comments end with periods.

A few comments lack trailing periods.

-// MergeContext tracks file paths and import chains during merge operations
+// MergeContext tracks file paths and import chains during merge operations.

-// No context available, return original error unchanged
+// No context available, return original error unchanged.

-// Build context message (without the original error text)
+// Build context message (without the original error text).

-// Add current file being processed
+// Add current file being processed.

-// Add import chain if available
+// Add import chain if available.

-// Add any additional information
+// Add any additional information.

-// Add helpful hints for common merge errors
+// Add helpful hints for common merge errors.

-// If we have context to add, wrap the error with the context message
+// If we have context to add, wrap the error with the context message.

-// No context was added, return original error
+// No context was added, return original error.

Also applies to: 64-64, 70-71, 76-76, 93-93, 105-105, 125-125, 130-130

pkg/merge/merge.go (3)

65-69: Log errors as error values, not strings.

Pass the error itself to the logger for richer, structured output.

- log.Debug("Merge operation failed", "error", err.Error())
+ log.Debug("Merge operation failed", "err", err)

- log.Debug("Merge failed with context",
+ log.Debug("Merge failed with context",
   "file", context.CurrentFile,
   "import_chain", context.GetImportChainString(),
-  "error", err.Error())
+  "err", err)

Also applies to: 176-182


20-22: Fix godot lints: add periods to comment lines and tighten doc comments.

Some comments don’t end with periods; also rephrase the function doc comments to full sentences.

-// MergeWithOptions takes a list of maps and options as input, deep-merges the items in the order they are defined in the list,
-// and returns a single map with the merged contents.
+// MergeWithOptions takes a list of maps and options as input. It deep-merges the items in the order they are defined in the list and returns a single map with the merged contents.

-// Due to a bug in `mergo.Merge`
+// Due to a bug in `mergo.Merge`.
-// (Note: in the `for` loop, it DOES modify the source of the previous loop iteration if it's a complex map and `mergo` gets a pointer to it,
-// not only the destination of the current loop iteration),
-// we don't give it our maps directly; we convert them to YAML strings and then back to `Go` maps,
-// so `mergo` does not have access to the original pointers
+// (Note: in the `for` loop, it DOES modify the source of the previous loop iteration if it's a complex map and `mergo` gets a pointer to it,
+// not only the destination of the current loop iteration).
+// We don't give it our maps directly; we convert them to YAML strings and then back to `Go` maps,
+// so `mergo` does not have access to the original pointers.

-// This was fixed/broken in https://github.com/imdario/mergo/pull/231/files
-// It was released in https://github.com/imdario/mergo/releases/tag/v0.3.14
-// It was not working before in `github.com/imdario/mergo` so we need to disable it in our code
+// This was fixed/broken in https://github.com/imdario/mergo/pull/231/files.
+// It was released in https://github.com/imdario/mergo/releases/tag/v0.3.14.
+// It was not working before in `github.com/imdario/mergo`, so we need to disable it in our code.

-// Merge takes a list of maps as input, deep-merges the items in the order they are defined in the list, and returns a single map with the merged contents.
+// Merge takes a list of maps as input, deep-merges the items in the order they are defined in the list, and returns a single map with the merged contents.

-// Check for nil config to prevent panic
+// Check for nil config to prevent panic.

-// Default to replace strategy if strategy is empty
+// Default to replace strategy if strategy is empty.

-// Check for nil config to prevent panic
+// Check for nil config to prevent panic.

-// Default to replace strategy if strategy is empty
+// Default to replace strategy if strategy is empty.

-// Log merge context if available (only in trace/debug mode to avoid noise)
+// Log merge context if available (only in trace/debug mode to avoid noise).

-// Log the error with context for debugging
+// Log the error with context for debugging.

-// Add context information to the error
+// Add context information to the error.

Also applies to: 36-41, 54-58, 75-76, 80-80, 85-85, 120-120, 129-129, 169-169, 176-176, 184-184


29-35: Idiomatic range loop.

Slight cleanup: range over values directly.

-for index := range inputs {
-	current := inputs[index]
+for _, current := range inputs {
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 942d91b and 41c4879.

📒 Files selected for processing (3)
  • pkg/merge/merge.go (3 hunks)
  • pkg/merge/merge_context.go (1 hunks)
  • pkg/merge/merge_no_duplicate_errors_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/merge/merge_no_duplicate_errors_test.go
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*.go: Use Viper for managing configuration, environment variables, and flags
Use interfaces for external dependencies to facilitate mocking
All code must pass golangci-lint checks
Follow Go's error handling idioms
Use meaningful error messages
Wrap errors with context using fmt.Errorf("context: %w", err)
Consider using a custom error type for domain-specific errors
Follow standard Go coding style
Use gofmt and goimports to format code
Prefer short, descriptive variable names
Use snake_case for environment variables
Document all exported functions, types, and methods
Document complex logic with inline comments
Follow Go's documentation conventions
Use Viper for configuration management
Support configuration via files, environment variables, and flags
Follow the precedence order: flags > environment variables > config file > defaults

**/*.go: All comments in Go code must end with periods (enforced by golangci-lint godot).
Wrap all returned errors using static errors from the errors package; never return dynamic errors directly.
Always bind environment variables with viper.BindEnv() and provide ATMOS_ alternatives for each external var.
Separate structured logging from UI output: use stderr for prompts/errors to user; stdout only for data; never use logging for UI.
Most text UI must go to stderr; only data/results to stdout. Prefer utils.PrintfMessageToTUI for UI messages.
For non-standard execution paths, capture telemetry with telemetry.CaptureCmd or telemetry.CaptureCmdString and never capture user data.
Ensure cross-platform compatibility: prefer SDKs to external binaries, use filepath/os/runtime for portability, and add build constraints when needed.

Files:

  • pkg/merge/merge_context.go
  • pkg/merge/merge.go
🧠 Learnings (5)
📚 Learning: 2025-07-01T02:22:25.901Z
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*.go : Wrap errors with context using `fmt.Errorf("context: %w", err)`

Applied to files:

  • pkg/merge/merge_context.go
  • pkg/merge/merge.go
📚 Learning: 2025-09-10T22:38:42.212Z
Learnt from: Benbentwo
PR: cloudposse/atmos#1475
File: pkg/auth/identities/aws/user.go:141-145
Timestamp: 2025-09-10T22:38:42.212Z
Learning: The user confirmed that the errors package has an error string wrapping format, contradicting the previous learning about ErrWrappingFormat being invalid. The current usage of fmt.Errorf(errUtils.ErrWrappingFormat, errUtils.ErrAuthAwsFileManagerFailed, err) appears to be the correct pattern.

Applied to files:

  • pkg/merge/merge_context.go
📚 Learning: 2025-09-13T18:06:07.674Z
Learnt from: samtholiya
PR: cloudposse/atmos#1466
File: toolchain/list.go:39-42
Timestamp: 2025-09-13T18:06:07.674Z
Learning: In the cloudposse/atmos repository, for UI messages in the toolchain package, use utils.PrintfMessageToTUI instead of log.Error or fmt.Fprintln(os.Stderr, ...). Import pkg/utils with alias "u" to follow the established pattern.

Applied to files:

  • pkg/merge/merge.go
📚 Learning: 2025-09-07T15:13:17.831Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-07T15:13:17.831Z
Learning: Applies to pkg/ui/theme/colors.go : Use theme.Colors constants (e.g., ColorGreen, ColorCyan, ColorRed, ColorSelectedItem, ColorBorder) for UI colors.

Applied to files:

  • pkg/merge/merge.go
📚 Learning: 2025-07-05T20:59:02.914Z
Learnt from: aknysh
PR: cloudposse/atmos#1363
File: internal/exec/template_utils.go:18-18
Timestamp: 2025-07-05T20:59:02.914Z
Learning: In the Atmos project, gomplate v4 is imported with a blank import (`_ "github.com/hairyhenderson/gomplate/v4"`) alongside v3 imports to resolve AWS SDK version conflicts. V3 uses older AWS SDK versions that conflict with newer AWS modules used by Atmos. A full migration to v4 requires extensive refactoring due to API changes and should be handled in a separate PR.

Applied to files:

  • pkg/merge/merge.go
🧬 Code graph analysis (2)
pkg/merge/merge_context.go (1)
cmd/cmd_utils.go (1)
  • Contains (762-769)
pkg/merge/merge.go (3)
pkg/schema/schema.go (2)
  • AtmosConfiguration (25-60)
  • Settings (834-838)
pkg/merge/merge_context.go (1)
  • MergeContext (10-20)
errors/errors.go (3)
  • ErrMerge (81-81)
  • ErrAtmosConfigIsNil (79-79)
  • ErrInvalidListMergeStrategy (80-80)
⏰ 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). (5)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Build (ubuntu-latest, linux)
  • GitHub Check: Lint (golangci)
  • GitHub Check: Analyze (go)
  • GitHub Check: Summary
🔇 Additional comments (2)
pkg/merge/merge_context.go (1)

57-132: Sentinel preservation in FormatError looks correct; please confirm with a regression test.

You’re now returning fmt.Errorf("%s: %w", ctx, err), which keeps ErrMerge discoverable via errors.Is — this addresses the earlier concern.

Run to confirm a test exists (or add one if missing):

#!/bin/bash
rg -nP --type=go 'Test.*FormatError.*ErrMerge|errors\.Is\([^)]*,\s*errUtils\.ErrMerge\)' -g '!**/vendor/**'
pkg/merge/merge.go (1)

114-160: Good: no double-formatting of context-wrapped errors.

Returning the result from MergeWithOptionsAndContext directly avoids duplicate context decoration.

coderabbitai[bot]
coderabbitai Bot previously approved these changes Sep 22, 2025
- Fixed schema.StacksConfiguration to schema.Stacks
- Fixed schema.ComponentsTerraform to schema.Terraform
- These type names were incorrect causing compilation errors

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (6)
internal/exec/validate_stacks_test.go (6)

3-12: Import require and the merge package to strengthen tests and exercise context API.
Add require for fail-fast assertions and import the merge package to call the context-aware API directly.

 import (
 	"path/filepath"
 	"strings"
 	"testing"
 
 	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
 
 	"github.com/cloudposse/atmos/pkg/schema"
 	u "github.com/cloudposse/atmos/pkg/utils"
+	"github.com/cloudposse/atmos/pkg/merge"
 )

119-132: Assert on the context in the error rather than logging.
Strengthen the test to fail on regressions.

-	if err != nil {
-		errStr := err.Error()
-		t.Logf("Processing error (expected): %s", errStr)
-
-		// Check if error contains context about the import chain
-		// The actual error format will depend on where the merge fails
-		if strings.Contains(errStr, "base") ||
-			strings.Contains(errStr, "override") ||
-			strings.Contains(errStr, "test-environment") {
-			t.Log("Error contains file references - context tracking is working")
-		}
-	} else {
-		t.Log("No error occurred - merge might have succeeded with current strategy")
-	}
+	require.Error(t, err, "expected a merge error with context.")
+	errStr := err.Error()
+	assert.Contains(t, errStr, "Import chain:", "should include import chain.")
+	assert.True(t,
+		strings.Contains(errStr, "base") ||
+			strings.Contains(errStr, "override") ||
+			strings.Contains(errStr, "test-environment"),
+		"should reference files in the chain.")

148-156: Don't ignore errors from filepath.Abs.
Avoid hidden failures in CI.

-				absPath, _ := filepath.Abs(testCasesPath)
+				absPath, err2 := filepath.Abs(testCasesPath)
+				require.NoError(t, err2)

168-181: Assert on error and on each expected part.
Replace logging with actionable assertions.

 		t.Run(tt.name, func(t *testing.T) {
 			err := tt.setupFunc()
-			if err != nil {
-				errStr := err.Error()
-				t.Logf("Formatted error:\n%s", errStr)
-
-				for _, part := range tt.expectedParts {
-					if part != "" && !strings.Contains(errStr, part) {
-						t.Logf("Warning: Expected part not found: %s", part)
-					}
-				}
-			}
+			require.Error(t, err, "expected an error for mismatch formatting.")
+			errStr := err.Error()
+			for _, part := range tt.expectedParts {
+				if part == "" {
+					continue
+				}
+				assert.Contains(t, errStr, part)
+			}
 		})

15-16: Fix godot-lint: make comments end with periods.
Several comments lack trailing periods; golangci-lint (godot) will flag them. Touch up across the file.

Also applies to: 22-23, 47-49, 55-56, 59-60, 67-74, 79-81, 93-94, 101-102, 123-129, 135-138


14-76: Add a happy-path test to satisfy guidelines (both success and error).
You only exercise error flows here. Add one valid fixture/run to assert ValidateStacks returns nil.

Proposed outline (add as a new test):

func TestValidateStacks_HappyPath(t *testing.T) {
  // Arrange: point to a known-good fixture (e.g., ../../tests/test-cases/validate-ok).
  // Act: call ValidateStacks.
  // Assert: require.NoError(t, err).
}

Also applies to: 78-133, 135-183

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 41c4879 and d9fa4e3.

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

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*.go: Use Viper for managing configuration, environment variables, and flags
Use interfaces for external dependencies to facilitate mocking
All code must pass golangci-lint checks
Follow Go's error handling idioms
Use meaningful error messages
Wrap errors with context using fmt.Errorf("context: %w", err)
Consider using a custom error type for domain-specific errors
Follow standard Go coding style
Use gofmt and goimports to format code
Prefer short, descriptive variable names
Use snake_case for environment variables
Document all exported functions, types, and methods
Document complex logic with inline comments
Follow Go's documentation conventions
Use Viper for configuration management
Support configuration via files, environment variables, and flags
Follow the precedence order: flags > environment variables > config file > defaults

**/*.go: All comments in Go code must end with periods (enforced by golangci-lint godot).
Wrap all returned errors using static errors from the errors package; never return dynamic errors directly.
Always bind environment variables with viper.BindEnv() and provide ATMOS_ alternatives for each external var.
Separate structured logging from UI output: use stderr for prompts/errors to user; stdout only for data; never use logging for UI.
Most text UI must go to stderr; only data/results to stdout. Prefer utils.PrintfMessageToTUI for UI messages.
For non-standard execution paths, capture telemetry with telemetry.CaptureCmd or telemetry.CaptureCmdString and never capture user data.
Ensure cross-platform compatibility: prefer SDKs to external binaries, use filepath/os/runtime for portability, and add build constraints when needed.

Files:

  • internal/exec/validate_stacks_test.go
**/*_test.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*_test.go: Every new feature must include comprehensive unit tests
Test both happy paths and error conditions
Use table-driven tests for testing multiple scenarios
Include integration tests for command flows
Test CLI end-to-end when possible
Use test fixtures for complex inputs
Consider using testify/mock for creating mock implementations

**/*_test.go: Always use t.Skipf() with a reason for skipped tests; never use t.Skip() or reasonless t.Skipf().
Test files must mirror implementation structure and naming (e.g., aws_ssm_store_test.go).
Use table-driven unit tests and mock interfaces for external dependencies; target >80% coverage.

Files:

  • internal/exec/validate_stacks_test.go
🧠 Learnings (5)
📚 Learning: 2024-11-13T21:37:07.852Z
Learnt from: Cerebrovinny
PR: cloudposse/atmos#764
File: internal/exec/describe_stacks.go:289-295
Timestamp: 2024-11-13T21:37:07.852Z
Learning: In the `internal/exec/describe_stacks.go` file of the `atmos` project written in Go, avoid extracting the stack name handling logic into a helper function within the `ExecuteDescribeStacks` method, even if the logic appears duplicated.

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2025-09-07T15:13:17.831Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-07T15:13:17.831Z
Learning: Applies to internal/exec/stack_processor_utils.go : Stack processing utilities should reside here; test multiple inheritance scenarios.

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2024-10-20T00:41:57.135Z
Learnt from: haitham911
PR: cloudposse/atmos#731
File: internal/exec/validate_stacks.go:93-98
Timestamp: 2024-10-20T00:41:57.135Z
Learning: When downloading schema files in `internal/exec/validate_stacks.go`, use a consistent temporary file name to overwrite the file each time and avoid creating multiple temporary files.

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2025-07-01T02:22:25.901Z
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*_test.go : Test both happy paths and error conditions

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2025-01-09T22:27:25.538Z
Learnt from: samtholiya
PR: cloudposse/atmos#914
File: cmd/validate_stacks.go:20-23
Timestamp: 2025-01-09T22:27:25.538Z
Learning: The validate commands in Atmos can have different help handling implementations. Specifically, validate_component.go and validate_stacks.go are designed to handle help requests differently, with validate_stacks.go including positional argument checks while validate_component.go does not.

Applied to files:

  • internal/exec/validate_stacks_test.go
🧬 Code graph analysis (1)
internal/exec/validate_stacks_test.go (4)
pkg/schema/schema.go (7)
  • AtmosConfiguration (25-60)
  • Stacks (352-358)
  • Logs (365-368)
  • Components (346-350)
  • Terraform (306-318)
  • Settings (834-838)
  • AtmosSettings (226-246)
internal/exec/validate_stacks.go (1)
  • ValidateStacks (64-202)
internal/exec/stack_processor_utils.go (1)
  • ProcessYAMLConfigFile (158-201)
pkg/stack/stack_processor.go (1)
  • ProcessYAMLConfigFile (38-79)
⏰ 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). (6)
  • GitHub Check: Build (macos-latest, macos)
  • GitHub Check: Build (ubuntu-latest, linux)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Analyze (go)
  • GitHub Check: Lint (golangci)
  • GitHub Check: Summary

Comment thread internal/exec/validate_stacks_test.go Resolved
Comment thread internal/exec/validate_stacks_test.go Resolved
Comment thread internal/exec/validate_stacks_test.go Resolved
Comment thread internal/exec/validate_stacks_test.go Resolved
@codecov

codecov Bot commented Sep 22, 2025 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.48148% with 23 lines in your changes missing coverage. Please review.
✅ Project coverage is 56.75%. Comparing base (0180dbb) to head (82aa34d).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
pkg/merge/merge.go 79.59% 9 Missing and 1 partial ⚠️
internal/exec/stack_processor_utils.go 87.69% 6 Missing and 2 partials ⚠️
pkg/merge/merge_context.go 95.69% 3 Missing and 1 partial ⚠️
internal/exec/version.go 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1494      +/-   ##
==========================================
+ Coverage   56.37%   56.75%   +0.38%     
==========================================
  Files         279      280       +1     
  Lines       29474    29708     +234     
==========================================
+ Hits        16616    16862     +246     
+ Misses      11046    11031      -15     
- Partials     1812     1815       +3     
Flag Coverage Δ
unittests 56.75% <91.48%> (+0.38%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

…d describe commands

Enhanced error reporting for merge type mismatches with file context and import chain tracking:

- Added MergeContext to track file processing and import chains during deep merging
- Enhanced error messages now show:
  - File being processed when error occurred
  - Complete import chain with proper indentation
  - Helpful debugging hints for common type mismatch issues
  - Configuration keywords (vars, settings, overrides) in backticks
- Improved formatting with markdown code fences to preserve indentation in terminal output
- Fixed duplicate error reporting in validate stacks command
- Removed verbose debug logs for cleaner output
- Added comprehensive test cases simulating YAML functions with deep merging
- Extended enhanced error reporting to both validate stacks and describe component commands
- Only process top-level stack files to avoid processing imported files multiple times

This provides much better debugging experience when users encounter type mismatches
in their stack configurations, making it clear which files are involved and how
they are related through imports.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
Comment thread pkg/merge/merge_context.go Fixed
Comment thread pkg/merge/merge_context.go Fixed

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
internal/exec/validate_stacks.go (1)

155-184: Bug: importedFiles keys omit extensions; comparison uses a path with extension.

importsConfig uses relative paths without extensions; here you compare against relativeFilePath (with extension), so imported files won’t be skipped and may be validated twice.

Apply this diff to normalize the key before lookup:

@@
-    relativeFilePath := u.TrimBasePathFromPath(atmosConfig.StacksBaseAbsolutePath+"/", filePath)
+    relativeFilePath := u.TrimBasePathFromPath(atmosConfig.StacksBaseAbsolutePath+"/", filePath)
+    // Normalize like importsConfig: compare without extension.
+    ext := filepath.Ext(relativeFilePath)
+    if ext == "" {
+        ext = u.DefaultStackConfigFileExtension
+    }
+    relativeFilePathNoExt := strings.TrimSuffix(relativeFilePath, ext)
@@
-    if importedFiles[relativeFilePath] {
+    if importedFiles[relativeFilePathNoExt] {
         log.Debug("Skipping imported file (will be processed via parent)", "file", relativeFilePath)
         continue
     }
internal/exec/stack_processor_utils.go (1)

60-98: Data race potential: shared errorResult mutated by goroutines.

Multiple goroutines can write errorResult concurrently. Use a channel or a mutex-guarded setter.

@@
- var errorResult error
+ errCh := make(chan error, count)
@@
-        go func(i int, p string) {
+        go func(i int, p string) {
           defer wg.Done()
@@
-          if err != nil {
-            errorResult = err
-            return
-          }
+          if err != nil {
+            errCh <- err
+            return
+          }
@@
-          if err != nil {
-            errorResult = err
-            return
-          }
+          if err != nil {
+            errCh <- err
+            return
+          }
@@
-          if err != nil {
-            errorResult = err
-            return
-          }
+          if err != nil {
+            errCh <- err
+            return
+          }
@@
- wg.Wait()
-
- if errorResult != nil {
-   return nil, nil, nil, errorResult
- }
+ wg.Wait()
+ close(errCh)
+ if len(errCh) > 0 {
+   return nil, nil, nil, <-errCh
+ }
🧹 Nitpick comments (4)
tests/test-cases/validate-type-mismatch/stacks/yaml-function-simulation.yaml (1)

25-27: YAML merge key is not referencing an alias—confirm intent.

<<: with an inline mapping doesn’t merge from vars.dynamic_config; it just injects the provided mapping. If the goal is to test anchor/alias merge semantics, consider anchoring dynamic_config and using <<: *anchor. If the goal is merely to set a conflicting value, current form is fine.

Would you like this to exercise true YAML merge semantics? If yes, I can propose an anchored variant.

internal/exec/validate_stacks.go (1)

160-184: Remove unused accumulator.

allImportsConfig is written but never read.

-    allImportsConfig := make(map[string]map[string]any)
@@
-        for importPath := range importsConfig {
-            importedFiles[importPath] = true
-            allImportsConfig[importPath] = importsConfig[importPath]
-        }
+        for importPath := range importsConfig {
+            importedFiles[importPath] = true
+        }
internal/exec/stack_processor_utils.go (2)

283-291: Wrap YAML template errors with a static sentinel.

Else path returns a dynamic error. Wrap it with ErrMerge (or a dedicated sentinel) to satisfy lint and keep consistent handling.

-      e := fmt.Errorf("invalid stack manifest '%s'\n%v%s", relativeFilePath, err, stackManifestTemplatesErrorMessage)
+      e := fmt.Errorf("%w: invalid stack manifest '%s': %v%s", errUtils.ErrMerge, relativeFilePath, err, stackManifestTemplatesErrorMessage)
       return nil, nil, nil, nil, nil, nil, nil, e

300-307: Wrap YAML unmarshal errors with a static sentinel.

Same pattern as above.

-      e := fmt.Errorf("invalid stack manifest '%s'\n%v%s", relativeFilePath, err, stackManifestTemplatesErrorMessage)
+      e := fmt.Errorf("%w: invalid stack manifest '%s': %v%s", errUtils.ErrMerge, relativeFilePath, err, stackManifestTemplatesErrorMessage)
       return nil, nil, nil, nil, nil, nil, nil, e
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between d9fa4e3 and 3b9a8ff.

📒 Files selected for processing (21)
  • internal/exec/stack_processor_utils.go (11 hunks)
  • internal/exec/validate_stacks.go (2 hunks)
  • pkg/merge/merge.go (2 hunks)
  • pkg/merge/merge_context.go (1 hunks)
  • tests/test-cases/validate-type-mismatch/atmos.yaml (1 hunks)
  • tests/test-cases/validate-type-mismatch/stacks/anchors-and-merges.yaml (1 hunks)
  • tests/test-cases/validate-type-mismatch/stacks/complex-import-chain.yaml (1 hunks)
  • tests/test-cases/validate-type-mismatch/stacks/config1.yaml (1 hunks)
  • tests/test-cases/validate-type-mismatch/stacks/config2.yaml (1 hunks)
  • tests/test-cases/validate-type-mismatch/stacks/deep-merge-test.yaml (1 hunks)
  • tests/test-cases/validate-type-mismatch/stacks/demo-error.yaml (1 hunks)
  • tests/test-cases/validate-type-mismatch/stacks/example1.yaml (1 hunks)
  • tests/test-cases/validate-type-mismatch/stacks/example2.yaml (1 hunks)
  • tests/test-cases/validate-type-mismatch/stacks/include-simulation.yaml (1 hunks)
  • tests/test-cases/validate-type-mismatch/stacks/merge-conflict.yaml (1 hunks)
  • tests/test-cases/validate-type-mismatch/stacks/mixins/subnet-config.yaml (1 hunks)
  • tests/test-cases/validate-type-mismatch/stacks/shared/databases.yaml (1 hunks)
  • tests/test-cases/validate-type-mismatch/stacks/shared/network.yaml (1 hunks)
  • tests/test-cases/validate-type-mismatch/stacks/trigger-error.yaml (1 hunks)
  • tests/test-cases/validate-type-mismatch/stacks/type-mismatch-direct.yaml (1 hunks)
  • tests/test-cases/validate-type-mismatch/stacks/yaml-function-simulation.yaml (1 hunks)
✅ Files skipped from review due to trivial changes (6)
  • tests/test-cases/validate-type-mismatch/stacks/demo-error.yaml
  • tests/test-cases/validate-type-mismatch/stacks/deep-merge-test.yaml
  • tests/test-cases/validate-type-mismatch/stacks/mixins/subnet-config.yaml
  • tests/test-cases/validate-type-mismatch/stacks/example2.yaml
  • tests/test-cases/validate-type-mismatch/stacks/config2.yaml
  • tests/test-cases/validate-type-mismatch/stacks/shared/network.yaml
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/test-cases/validate-type-mismatch/atmos.yaml
🧰 Additional context used
📓 Path-based instructions (4)
tests/test-cases/**

📄 CodeRabbit inference engine (CLAUDE.md)

Never modify golden snapshot fixtures under tests/test-cases/ unless explicitly instructed.

Files:

  • tests/test-cases/validate-type-mismatch/stacks/example1.yaml
  • tests/test-cases/validate-type-mismatch/stacks/anchors-and-merges.yaml
  • tests/test-cases/validate-type-mismatch/stacks/include-simulation.yaml
  • tests/test-cases/validate-type-mismatch/stacks/type-mismatch-direct.yaml
  • tests/test-cases/validate-type-mismatch/stacks/trigger-error.yaml
  • tests/test-cases/validate-type-mismatch/stacks/merge-conflict.yaml
  • tests/test-cases/validate-type-mismatch/stacks/shared/databases.yaml
  • tests/test-cases/validate-type-mismatch/stacks/yaml-function-simulation.yaml
  • tests/test-cases/validate-type-mismatch/stacks/config1.yaml
  • tests/test-cases/validate-type-mismatch/stacks/complex-import-chain.yaml
**/*.{yaml,yml}

📄 CodeRabbit inference engine (CLAUDE.md)

YAML configs should support Go templating using provided template functions.

Files:

  • tests/test-cases/validate-type-mismatch/stacks/example1.yaml
  • tests/test-cases/validate-type-mismatch/stacks/anchors-and-merges.yaml
  • tests/test-cases/validate-type-mismatch/stacks/include-simulation.yaml
  • tests/test-cases/validate-type-mismatch/stacks/type-mismatch-direct.yaml
  • tests/test-cases/validate-type-mismatch/stacks/trigger-error.yaml
  • tests/test-cases/validate-type-mismatch/stacks/merge-conflict.yaml
  • tests/test-cases/validate-type-mismatch/stacks/shared/databases.yaml
  • tests/test-cases/validate-type-mismatch/stacks/yaml-function-simulation.yaml
  • tests/test-cases/validate-type-mismatch/stacks/config1.yaml
  • tests/test-cases/validate-type-mismatch/stacks/complex-import-chain.yaml
**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*.go: Use Viper for managing configuration, environment variables, and flags
Use interfaces for external dependencies to facilitate mocking
All code must pass golangci-lint checks
Follow Go's error handling idioms
Use meaningful error messages
Wrap errors with context using fmt.Errorf("context: %w", err)
Consider using a custom error type for domain-specific errors
Follow standard Go coding style
Use gofmt and goimports to format code
Prefer short, descriptive variable names
Use snake_case for environment variables
Document all exported functions, types, and methods
Document complex logic with inline comments
Follow Go's documentation conventions
Use Viper for configuration management
Support configuration via files, environment variables, and flags
Follow the precedence order: flags > environment variables > config file > defaults

**/*.go: All comments in Go code must end with periods (enforced by golangci-lint godot).
Wrap all returned errors using static errors from the errors package; never return dynamic errors directly.
Always bind environment variables with viper.BindEnv() and provide ATMOS_ alternatives for each external var.
Separate structured logging from UI output: use stderr for prompts/errors to user; stdout only for data; never use logging for UI.
Most text UI must go to stderr; only data/results to stdout. Prefer utils.PrintfMessageToTUI for UI messages.
For non-standard execution paths, capture telemetry with telemetry.CaptureCmd or telemetry.CaptureCmdString and never capture user data.
Ensure cross-platform compatibility: prefer SDKs to external binaries, use filepath/os/runtime for portability, and add build constraints when needed.

Files:

  • pkg/merge/merge_context.go
  • pkg/merge/merge.go
  • internal/exec/validate_stacks.go
  • internal/exec/stack_processor_utils.go
internal/exec/stack_processor_utils.go

📄 CodeRabbit inference engine (CLAUDE.md)

internal/exec/stack_processor_utils.go: Place core stack processing utilities here and reuse them.
Stack processing utilities should reside here; test multiple inheritance scenarios.

Files:

  • internal/exec/stack_processor_utils.go
🧠 Learnings (15)
📓 Common learnings
Learnt from: Listener430
PR: cloudposse/atmos#934
File: tests/fixtures/scenarios/docs-generate/README.md.gotmpl:99-118
Timestamp: 2025-01-25T03:51:57.689Z
Learning: For the cloudposse/atmos repository, changes to template contents should be handled in dedicated PRs and are typically considered out of scope for PRs focused on other objectives.
📚 Learning: 2025-03-17T18:41:08.831Z
Learnt from: haitham911
PR: cloudposse/atmos#1085
File: pkg/config/imports.go:68-75
Timestamp: 2025-03-17T18:41:08.831Z
Learning: In the Atmos configuration import system, errors during config file merging are logged at debug level and the process continues with other imports rather than failing completely, prioritizing resilience over strict correctness.

Applied to files:

  • tests/test-cases/validate-type-mismatch/stacks/include-simulation.yaml
📚 Learning: 2025-07-01T02:22:25.901Z
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*.go : Wrap errors with context using `fmt.Errorf("context: %w", err)`

Applied to files:

  • pkg/merge/merge_context.go
  • pkg/merge/merge.go
📚 Learning: 2025-09-10T22:38:42.212Z
Learnt from: Benbentwo
PR: cloudposse/atmos#1475
File: pkg/auth/identities/aws/user.go:141-145
Timestamp: 2025-09-10T22:38:42.212Z
Learning: The user confirmed that the errors package has an error string wrapping format, contradicting the previous learning about ErrWrappingFormat being invalid. The current usage of fmt.Errorf(errUtils.ErrWrappingFormat, errUtils.ErrAuthAwsFileManagerFailed, err) appears to be the correct pattern.

Applied to files:

  • pkg/merge/merge_context.go
📚 Learning: 2025-04-11T22:06:46.999Z
Learnt from: samtholiya
PR: cloudposse/atmos#1147
File: internal/exec/validate_schema.go:42-57
Timestamp: 2025-04-11T22:06:46.999Z
Learning: The "ExecuteAtmosValidateSchemaCmd" function in internal/exec/validate_schema.go has been reviewed and confirmed to have acceptable cognitive complexity despite static analysis warnings. The function uses a clean structure with only three if statements for error handling and delegates complex operations to helper methods.

Applied to files:

  • pkg/merge/merge_context.go
  • internal/exec/stack_processor_utils.go
📚 Learning: 2024-10-23T21:36:40.262Z
Learnt from: osterman
PR: cloudposse/atmos#740
File: cmd/cmd_utils.go:340-359
Timestamp: 2024-10-23T21:36:40.262Z
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.

Applied to files:

  • pkg/merge/merge_context.go
📚 Learning: 2025-09-07T15:13:17.831Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-07T15:13:17.831Z
Learning: Applies to pkg/ui/theme/colors.go : Use theme.Colors constants (e.g., ColorGreen, ColorCyan, ColorRed, ColorSelectedItem, ColorBorder) for UI colors.

Applied to files:

  • pkg/merge/merge.go
📚 Learning: 2025-09-13T18:06:07.674Z
Learnt from: samtholiya
PR: cloudposse/atmos#1466
File: toolchain/list.go:39-42
Timestamp: 2025-09-13T18:06:07.674Z
Learning: In the cloudposse/atmos repository, for UI messages in the toolchain package, use utils.PrintfMessageToTUI instead of log.Error or fmt.Fprintln(os.Stderr, ...). Import pkg/utils with alias "u" to follow the established pattern.

Applied to files:

  • pkg/merge/merge.go
📚 Learning: 2025-07-05T20:59:02.914Z
Learnt from: aknysh
PR: cloudposse/atmos#1363
File: internal/exec/template_utils.go:18-18
Timestamp: 2025-07-05T20:59:02.914Z
Learning: In the Atmos project, gomplate v4 is imported with a blank import (`_ "github.com/hairyhenderson/gomplate/v4"`) alongside v3 imports to resolve AWS SDK version conflicts. V3 uses older AWS SDK versions that conflict with newer AWS modules used by Atmos. A full migration to v4 requires extensive refactoring due to API changes and should be handled in a separate PR.

Applied to files:

  • pkg/merge/merge.go
📚 Learning: 2024-11-19T23:00:45.899Z
Learnt from: osterman
PR: cloudposse/atmos#795
File: internal/exec/stack_processor_utils.go:378-386
Timestamp: 2024-11-19T23:00:45.899Z
Learning: In the `ProcessYAMLConfigFile` function within `internal/exec/stack_processor_utils.go`, directory traversal in stack imports is acceptable and should not be restricted.

Applied to files:

  • internal/exec/validate_stacks.go
  • internal/exec/stack_processor_utils.go
📚 Learning: 2025-09-07T15:13:17.831Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-07T15:13:17.831Z
Learning: Applies to pkg/stack/** : Make stack processing changes in pkg/stack/ and validate inheritance/template rendering.

Applied to files:

  • internal/exec/validate_stacks.go
📚 Learning: 2024-12-07T16:19:01.683Z
Learnt from: aknysh
PR: cloudposse/atmos#825
File: internal/exec/terraform.go:30-30
Timestamp: 2024-12-07T16:19:01.683Z
Learning: In `internal/exec/terraform.go`, skipping stack validation when help flags are present is not necessary.

Applied to files:

  • internal/exec/validate_stacks.go
📚 Learning: 2024-10-20T00:41:57.135Z
Learnt from: haitham911
PR: cloudposse/atmos#731
File: internal/exec/validate_stacks.go:93-98
Timestamp: 2024-10-20T00:41:57.135Z
Learning: When downloading schema files in `internal/exec/validate_stacks.go`, use a consistent temporary file name to overwrite the file each time and avoid creating multiple temporary files.

Applied to files:

  • internal/exec/validate_stacks.go
📚 Learning: 2025-09-07T15:13:17.831Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-07T15:13:17.831Z
Learning: Applies to pkg/utils/yaml_utils.go : Prefer existing YAML processing utilities in pkg/utils/yaml_utils.go before adding new ones.

Applied to files:

  • internal/exec/stack_processor_utils.go
📚 Learning: 2024-12-07T16:16:13.038Z
Learnt from: Listener430
PR: cloudposse/atmos#825
File: internal/exec/helmfile_generate_varfile.go:28-31
Timestamp: 2024-12-07T16:16:13.038Z
Learning: In `internal/exec/helmfile_generate_varfile.go`, the `--help` command (`./atmos helmfile generate varfile --help`) works correctly without requiring stack configurations, and the only change needed was to make `ProcessCommandLineArgs` exportable by capitalizing its name.

Applied to files:

  • internal/exec/stack_processor_utils.go
🧬 Code graph analysis (3)
pkg/merge/merge.go (3)
pkg/schema/schema.go (2)
  • AtmosConfiguration (25-60)
  • Settings (834-838)
pkg/merge/merge_context.go (1)
  • MergeContext (10-20)
errors/errors.go (3)
  • ErrMerge (81-81)
  • ErrAtmosConfigIsNil (79-79)
  • ErrInvalidListMergeStrategy (80-80)
internal/exec/validate_stacks.go (3)
internal/exec/stack_processor_utils.go (2)
  • ProcessYAMLConfigFile (159-202)
  • ProcessStackConfig (643-2086)
pkg/stack/stack_processor.go (2)
  • ProcessYAMLConfigFile (38-79)
  • ProcessStackConfig (83-112)
pkg/utils/file_utils.go (1)
  • TrimBasePathFromPath (82-86)
internal/exec/stack_processor_utils.go (3)
pkg/merge/merge_context.go (2)
  • NewMergeContext (23-27)
  • MergeContext (10-20)
pkg/utils/file_utils.go (1)
  • TrimBasePathFromPath (82-86)
pkg/merge/merge.go (1)
  • MergeWithContext (113-158)
🪛 GitHub Check: golangci-lint
pkg/merge/merge_context.go

[failure] 58-58:
function-length: maximum number of lines per function exceeded; max 60 but got 67


[failure] 125-125:
do not define dynamic errors, use wrapped static errors instead: "fmt.Errorf("%s", sb.String())"

internal/exec/stack_processor_utils.go

[failure] 207-207:
cognitive complexity 173 of func ProcessYAMLConfigFileWithContext is high (> 20)


[failure] 288-288:
do not define dynamic errors, use wrapped static errors instead: "fmt.Errorf("invalid stack manifest '%s'\n%v%s", relativeFilePath, err, stackManifestTemplatesErrorMessage)"


[failure] 305-305:
do not define dynamic errors, use wrapped static errors instead: "fmt.Errorf("invalid stack manifest '%s'\n%v%s", relativeFilePath, err, stackManifestTemplatesErrorMessage)"

⏰ 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). (2)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Summary
🔇 Additional comments (19)
tests/test-cases/validate-type-mismatch/stacks/config1.yaml (1)

2-9: Looks good; minimal, valid stack input.

Structure is sound for exercising list-vs-scalar mismatches downstream. No action.

tests/test-cases/validate-type-mismatch/stacks/shared/databases.yaml (1)

2-18: Fixture reads clean and purposeful.

Good nested maps/lists to drive deep-merge cases. Nothing to change.

tests/test-cases/validate-type-mismatch/stacks/include-simulation.yaml (2)

27-36: Type-mismatch intents are clear.

Good targeted conflicts (subnets string vs array, availability_zones map vs array). No changes.

Also applies to: 41-44


6-15: Validate import targets and context schema.

  • include-simulation.yaml (tests/test-cases/validate-type-mismatch/stacks/include-simulation.yaml: lines 6-15) references tests/test-cases/validate-type-mismatch/stacks/shared/network.yaml and tests/test-cases/validate-type-mismatch/stacks/mixins/subnet-config.yaml — both files exist.
  • Search of pkg/ and internal/ returned no matches for the context keys component_type, component, or type; loader schema cannot be verified. Confirm the loader accepts these keys (or provide the loader/schema path) and update the YAML or loader to match.
tests/test-cases/validate-type-mismatch/stacks/anchors-and-merges.yaml (2)

19-21: Import path check — base.yaml present.
Confirmed: tests/test-cases/validate-type-mismatch/stacks/base.yaml. Ensure the test harness actually loads this import during test execution.


5-18: Verify YAML merge-key handling before approving

Anchors and merges in tests/test-cases/validate-type-mismatch/stacks/anchors-and-merges.yaml (lines 5–18) are correct and intentionally produce type mismatches. Sandbox search returned no results — cannot confirm which YAML loader the repo uses. Confirm the loader honors the YAML merge operator (<<) and anchors before approving.

Suggested local checks:

  • rg -n -S 'gopkg.in/yaml.v3|github.com/go-yaml/yaml|sigs.k8s.io/yaml|k8s.io/apimachinery/pkg/util/yaml|yaml.Unmarshal|yaml.NewDecoder|UnmarshalYAML'
  • rg -n -S '<<:'
tests/test-cases/validate-type-mismatch/stacks/complex-import-chain.yaml (2)

2-8: Confirm multi-hop imports exist — verified.

Both files are present: tests/test-cases/validate-type-mismatch/stacks/base.yaml and tests/test-cases/validate-type-mismatch/stacks/deep-merge-test.yaml.


16-23: Verify metadata.inherits is consumed or intentionally ignored.
Search returned no references (ripgrep: "No files were searched"); confirm the test's metadata.inherits is used by the code under test or remove/document it.
Location: tests/test-cases/validate-type-mismatch/stacks/complex-import-chain.yaml:16-23

tests/test-cases/validate-type-mismatch/stacks/yaml-function-simulation.yaml (1)

6-10: Confirmed — shared fixtures exist.
Both tests/test-cases/validate-type-mismatch/stacks/shared/network.yaml and tests/test-cases/validate-type-mismatch/stacks/shared/databases.yaml are present.

tests/test-cases/validate-type-mismatch/stacks/type-mismatch-direct.yaml (1)

4-10: Confirm test picks up fixtures (base.yaml, override.yaml)

Both files exist at tests/test-cases/validate-type-mismatch/stacks/, but no direct references to type-mismatch-direct.yaml were found in tests — verify the test harness dynamically discovers fixtures in that directory or add an explicit test reference.

tests/test-cases/validate-type-mismatch/stacks/trigger-error.yaml (1)

2-4: Verify import resolution for bare names and file presence

  • Verified: tests/test-cases/validate-type-mismatch/stacks/config2.yaml exists.
  • Action: confirm tests/test-cases/validate-type-mismatch/stacks/config1.yaml is present and that your import resolver accepts bare names (import: - config1 / - config2). If not, change to explicit paths or include .yaml / path: in tests/test-cases/validate-type-mismatch/stacks/trigger-error.yaml (lines 2–4).
tests/test-cases/validate-type-mismatch/stacks/merge-conflict.yaml (1)

1-7: LGTM.

Fixture looks minimal and aligned with the test intent. No changes requested.

tests/test-cases/validate-type-mismatch/stacks/example1.yaml (1)

1-14: LGTM.

Good representative nested structure for exercising type mismatches.

pkg/merge/merge.go (3)

64-67: Good: single-source error emission with sentinel.

Returns are wrapped with ErrMerge and no direct stderr writes. Nice.


112-158: Context-aware API surface looks correct.

Nil-config and invalid-strategy checks are wrapped and optionally formatted via context. Parameters/defaults read cleanly.


160-183: No double-formatting.

Delegation to MergeWithOptionsAndContext without re-wrapping avoids duplicated context.

internal/exec/stack_processor_utils.go (2)

236-241: Nice: always have a MergeContext.

Initializes and tags each file; this enables import-chain context even when caller didn’t pass a context.


393-406: Good: merged all critical paths via MergeWithContext.

This centralizes context-enriched failures and removes duplicate printing.

Also applies to: 402-409, 541-559, 553-559, 576-583, 586-593, 626-630

pkg/merge/merge_context.go (1)

57-126: Preserve error sentinels — wrap the original error and avoid duplicating its message.

FormatError currently rebuilds and returns fmt.Errorf("%s", ...), which drops sentinel errors (e.g., ErrMerge) and duplicates err.Error(); change the return to wrap the original error (fmt.Errorf("%w\n%s", err, sb.String())) and extract the hint-building into a helper (buildMergeHints). Fix: pkg/merge/merge_context.go (FormatError, lines 57–126). Regression test added: pkg/merge/merge_context_preserve_error_test.go asserts errors.Is(got, errUtils.ErrMerge).

- Fixed TestMergeContext_FormatError test by updating expected strings to match new markdown formatting
- Fixed unused lambda warning by simplifying test setup function
- Fixed godot linter warnings by adding periods to all comment endings
- Added static error ErrInvalidStackManifest to avoid dynamic error creation
- Fixed filepathJoin warnings by splitting path components correctly
- Fixed gofumpt formatting issues
- Fixed compilation errors in merge_with_context_test.go (continue -> return)
- Added nolint directives for complex functions that would require major refactoring:
  - ProcessYAMLConfigFileWithContext: High cyclomatic complexity due to import processing logic
  - FormatError: Extended function length due to comprehensive error formatting
- Only process top-level stack files in validation to avoid duplicate error reporting

All tests passing and lint checks clean.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
internal/exec/stack_processor_utils.go (4)

94-99: Data race on shared errorResult in concurrent loop.

Multiple goroutines write errorResult without synchronization. Guard writes or use errgroup.

   var wg sync.WaitGroup
   wg.Add(count)
+  var errMu sync.Mutex
@@
-      if err != nil {
-        errorResult = err
-        return
-      }
+      if err != nil {
+        errMu.Lock()
+        if errorResult == nil {
+          errorResult = err
+        }
+        errMu.Unlock()
+        return
+      }
@@
-      if err != nil {
-        errorResult = err
-        return
-      }
+      if err != nil {
+        errMu.Lock()
+        if errorResult == nil {
+          errorResult = err
+        }
+        errMu.Unlock()
+        return
+      }

Also applies to: 123-126, 53-60


329-357: Close the opened schema file; wrap errors with static type and context.

Leak: os.Open handle is never closed. Also, use ErrInvalidStackManifest and mergeContext.FormatError(...) instead of dynamic errors.Errorf.

- atmosManifestJsonSchemaValidationErrorFormat := "Atmos manifest JSON Schema validation error in the file '%s':\n%v"
+ atmosManifestJsonSchemaValidationErrorFormat := "Atmos manifest JSON Schema validation error in the file '%s':\n%v"
+ wrapSchemaErr := func(inner error) error {
+   e := fmt.Errorf("%w: %s", errUtils.ErrInvalidStackManifest,
+     fmt.Sprintf(atmosManifestJsonSchemaValidationErrorFormat, relativeFilePath, inner))
+   if mergeContext != nil {
+     return mergeContext.FormatError(e)
+   }
+   return e
+ }
@@
- atmosManifestJsonSchemaFileReader, err := os.Open(atmosManifestJsonSchemaFilePath)
+ atmosManifestJsonSchemaFileReader, err := os.Open(atmosManifestJsonSchemaFilePath)
   if err != nil {
-    return nil, nil, nil, nil, nil, nil, nil, errors.Errorf(atmosManifestJsonSchemaValidationErrorFormat, relativeFilePath, err)
+    return nil, nil, nil, nil, nil, nil, nil, wrapSchemaErr(err)
   }
+ defer func() { _ = atmosManifestJsonSchemaFileReader.Close() }()
@@
- if err := compiler.AddResource(atmosManifestJsonSchemaFilePath, atmosManifestJsonSchemaFileReader); err != nil {
-   return nil, nil, nil, nil, nil, nil, nil, errors.Errorf(atmosManifestJsonSchemaValidationErrorFormat, relativeFilePath, err)
- }
+ if err := compiler.AddResource(atmosManifestJsonSchemaFilePath, atmosManifestJsonSchemaFileReader); err != nil {
+   return nil, nil, nil, nil, nil, nil, nil, wrapSchemaErr(err)
+ }
@@
- compiledSchema, err := compiler.Compile(atmosManifestJsonSchemaFilePath)
- if err != nil {
-   return nil, nil, nil, nil, nil, nil, nil, errors.Errorf(atmosManifestJsonSchemaValidationErrorFormat, relativeFilePath, err)
- }
+ compiledSchema, err := compiler.Compile(atmosManifestJsonSchemaFilePath)
+ if err != nil {
+   return nil, nil, nil, nil, nil, nil, nil, wrapSchemaErr(err)
+ }
@@
- if err = compiledSchema.Validate(dataFromJson); err != nil {
+ if err = compiledSchema.Validate(dataFromJson); err != nil {
    switch e := err.(type) {
    case *jsonschema.ValidationError:
      b, err2 := json.MarshalIndent(e.BasicOutput(), "", "  ")
      if err2 != nil {
-       return nil, nil, nil, nil, nil, nil, nil, errors.Errorf(atmosManifestJsonSchemaValidationErrorFormat, relativeFilePath, err2)
+       return nil, nil, nil, nil, nil, nil, nil, wrapSchemaErr(err2)
      }
-     return nil, nil, nil, nil, nil, nil, nil, errors.Errorf(atmosManifestJsonSchemaValidationErrorFormat, relativeFilePath, string(b))
+     return nil, nil, nil, nil, nil, nil, nil, wrapSchemaErr(fmt.Errorf("%s", string(b)))
    default:
-     return nil, nil, nil, nil, nil, nil, nil, errors.Errorf(atmosManifestJsonSchemaValidationErrorFormat, relativeFilePath, err)
+     return nil, nil, nil, nil, nil, nil, nil, wrapSchemaErr(err)
    }
  }

389-393: Fix copy/paste typo and wrap with static error.

Message references terraform in a Helmfile branch; use helmfile.overrides. Also wrap with ErrInvalidStackManifest.

- return nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("invalid 'terraform.overrides' section in the stack manifest '%s'", relativeFilePath)
+ return nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("%w: invalid 'helmfile.overrides' section in the stack manifest '%s'", errUtils.ErrInvalidStackManifest, relativeFilePath)

363-392: Prefer static errors + merge-context formatting for invalid sections and import errors.

Many returns use dynamic fmt.Errorf/errors.New. For new code, wrap with ErrInvalidStackManifest and, when available, mergeContext.FormatError(...) to keep error provenance consistent.

Example pattern (apply similarly to nearby returns):

- return nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("invalid 'overrides' section in the stack manifest '%s'", relativeFilePath)
+ e := fmt.Errorf("%w: invalid 'overrides' section in the stack manifest '%s'", errUtils.ErrInvalidStackManifest, relativeFilePath)
+ if mergeContext != nil { e = mergeContext.FormatError(e) }
+ return nil, nil, nil, nil, nil, nil, nil, e

And for import errors:

- return nil, nil, nil, nil, nil, nil, nil, errors.New(errorMessage)
+ e := fmt.Errorf("%w: %s", errUtils.ErrInvalidStackManifest, errorMessage)
+ if mergeContext != nil { e = mergeContext.FormatError(e) }
+ return nil, nil, nil, nil, nil, nil, nil, e

Also applies to: 423-467, 470-501, 503-512

🧹 Nitpick comments (3)
pkg/merge/merge_with_context_test.go (1)

124-159: Strengthen the logging test with an assertion.

Right now it never fails if nothing is logged. Add a minimal assertion that logOutput is non-empty when the invalid strategy path is hit.

-  logOutput := logBuffer.String()
-  if logOutput != "" {
-    // If logging is enabled, verify it contains relevant information
-    t.Logf("Log output: %s", logOutput)
-    // The exact format depends on the logger configuration
-  }
+  logOutput := logBuffer.String()
+  assert.NotEmpty(t, logOutput, "expected error to be logged for invalid strategy.")
internal/exec/validate_stacks_test.go (1)

138-165: Populate expected tokens and assert them.

Make this test meaningful but resilient to formatting changes.

   tests := []struct {
@@
       expectedParts: []string{
-        // We expect to see parts of the error message
-        // The exact format depends on the implementation
+        "cannot override two slices with different type",
+        "File being processed:",
+        "Import chain:",
       },

And assert each token:

-      for _, part := range tt.expectedParts {
-        if part != "" && !strings.Contains(errStr, part) {
-          t.Logf("Warning: Expected part not found: %s", part)
-        }
-      }
+      for _, part := range tt.expectedParts {
+        assert.Contains(t, errStr, part)
+      }
internal/exec/stack_processor_utils.go (1)

205-211: Add trailing periods to new comments to satisfy godot linter.

Minor style, but enforced here.

-// ProcessYAMLConfigFileWithContext takes a path to a YAML stack manifest,
-// recursively processes and deep-merges all the imports with context tracking,
-// and returns the final stack config.
+// ProcessYAMLConfigFileWithContext takes a path to a YAML stack manifest.
+// It recursively processes and deep-merges all the imports with context tracking.
+// It returns the final stack config.
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 3b9a8ff and 9ba1f32.

📒 Files selected for processing (8)
  • errors/errors.go (1 hunks)
  • internal/exec/stack_processor_utils.go (12 hunks)
  • internal/exec/validate_stacks_test.go (1 hunks)
  • pkg/merge/merge_context.go (1 hunks)
  • pkg/merge/merge_context_demo_test.go (1 hunks)
  • pkg/merge/merge_context_test.go (1 hunks)
  • pkg/merge/merge_no_duplicate_errors_test.go (1 hunks)
  • pkg/merge/merge_with_context_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • pkg/merge/merge_context_demo_test.go
  • pkg/merge/merge_context.go
  • pkg/merge/merge_no_duplicate_errors_test.go
  • pkg/merge/merge_context_test.go
🧰 Additional context used
📓 Path-based instructions (5)
**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*.go: Use Viper for managing configuration, environment variables, and flags
Use interfaces for external dependencies to facilitate mocking
All code must pass golangci-lint checks
Follow Go's error handling idioms
Use meaningful error messages
Wrap errors with context using fmt.Errorf("context: %w", err)
Consider using a custom error type for domain-specific errors
Follow standard Go coding style
Use gofmt and goimports to format code
Prefer short, descriptive variable names
Use snake_case for environment variables
Document all exported functions, types, and methods
Document complex logic with inline comments
Follow Go's documentation conventions
Use Viper for configuration management
Support configuration via files, environment variables, and flags
Follow the precedence order: flags > environment variables > config file > defaults

**/*.go: All comments in Go code must end with periods (enforced by golangci-lint godot).
Wrap all returned errors using static errors from the errors package; never return dynamic errors directly.
Always bind environment variables with viper.BindEnv() and provide ATMOS_ alternatives for each external var.
Separate structured logging from UI output: use stderr for prompts/errors to user; stdout only for data; never use logging for UI.
Most text UI must go to stderr; only data/results to stdout. Prefer utils.PrintfMessageToTUI for UI messages.
For non-standard execution paths, capture telemetry with telemetry.CaptureCmd or telemetry.CaptureCmdString and never capture user data.
Ensure cross-platform compatibility: prefer SDKs to external binaries, use filepath/os/runtime for portability, and add build constraints when needed.

Files:

  • errors/errors.go
  • internal/exec/validate_stacks_test.go
  • internal/exec/stack_processor_utils.go
  • pkg/merge/merge_with_context_test.go
errors/errors.go

📄 CodeRabbit inference engine (CLAUDE.md)

Define all static errors in errors/errors.go.

Files:

  • errors/errors.go
**/*_test.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*_test.go: Every new feature must include comprehensive unit tests
Test both happy paths and error conditions
Use table-driven tests for testing multiple scenarios
Include integration tests for command flows
Test CLI end-to-end when possible
Use test fixtures for complex inputs
Consider using testify/mock for creating mock implementations

**/*_test.go: Always use t.Skipf() with a reason for skipped tests; never use t.Skip() or reasonless t.Skipf().
Test files must mirror implementation structure and naming (e.g., aws_ssm_store_test.go).
Use table-driven unit tests and mock interfaces for external dependencies; target >80% coverage.

Files:

  • internal/exec/validate_stacks_test.go
  • pkg/merge/merge_with_context_test.go
internal/exec/stack_processor_utils.go

📄 CodeRabbit inference engine (CLAUDE.md)

internal/exec/stack_processor_utils.go: Place core stack processing utilities here and reuse them.
Stack processing utilities should reside here; test multiple inheritance scenarios.

Files:

  • internal/exec/stack_processor_utils.go
pkg/**/*_test.go

📄 CodeRabbit inference engine (CLAUDE.md)

Unit tests reside under pkg/ alongside implementations.

Files:

  • pkg/merge/merge_with_context_test.go
🧠 Learnings (22)
📚 Learning: 2024-11-13T21:37:07.852Z
Learnt from: Cerebrovinny
PR: cloudposse/atmos#764
File: internal/exec/describe_stacks.go:289-295
Timestamp: 2024-11-13T21:37:07.852Z
Learning: In the `internal/exec/describe_stacks.go` file of the `atmos` project written in Go, avoid extracting the stack name handling logic into a helper function within the `ExecuteDescribeStacks` method, even if the logic appears duplicated.

Applied to files:

  • internal/exec/validate_stacks_test.go
  • internal/exec/stack_processor_utils.go
📚 Learning: 2025-09-07T15:13:17.831Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-07T15:13:17.831Z
Learning: Applies to internal/exec/stack_processor_utils.go : Stack processing utilities should reside here; test multiple inheritance scenarios.

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2024-10-20T00:41:57.135Z
Learnt from: haitham911
PR: cloudposse/atmos#731
File: internal/exec/validate_stacks.go:93-98
Timestamp: 2024-10-20T00:41:57.135Z
Learning: When downloading schema files in `internal/exec/validate_stacks.go`, use a consistent temporary file name to overwrite the file each time and avoid creating multiple temporary files.

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2024-12-07T16:16:13.038Z
Learnt from: Listener430
PR: cloudposse/atmos#825
File: internal/exec/helmfile_generate_varfile.go:28-31
Timestamp: 2024-12-07T16:16:13.038Z
Learning: In `internal/exec/helmfile_generate_varfile.go`, the `--help` command (`./atmos helmfile generate varfile --help`) works correctly without requiring stack configurations, and the only change needed was to make `ProcessCommandLineArgs` exportable by capitalizing its name.

Applied to files:

  • internal/exec/validate_stacks_test.go
  • internal/exec/stack_processor_utils.go
📚 Learning: 2024-12-12T15:17:45.245Z
Learnt from: osterman
PR: cloudposse/atmos#808
File: examples/demo-atmos.d/atmos.d/tools/helmfile.yml:10-10
Timestamp: 2024-12-12T15:17:45.245Z
Learning: In `examples/demo-atmos.d/atmos.d/tools/helmfile.yml`, when suggesting changes to `kubeconfig_path`, ensure that the values use valid Go template syntax.

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2025-03-18T12:26:25.329Z
Learnt from: Listener430
PR: cloudposse/atmos#1149
File: tests/snapshots/TestCLICommands_atmos_vendor_pull_ssh.stderr.golden:7-7
Timestamp: 2025-03-18T12:26:25.329Z
Learning: In the Atmos project, typos or inconsistencies in test snapshot files (such as "terrafrom" instead of "terraform") may be intentional as they capture the exact output of commands and should not be flagged as issues requiring correction.

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2024-12-02T21:26:32.337Z
Learnt from: osterman
PR: cloudposse/atmos#808
File: pkg/config/config.go:478-483
Timestamp: 2024-12-02T21:26:32.337Z
Learning: In the 'atmos' project, when reviewing Go code like `pkg/config/config.go`, avoid suggesting file size checks after downloading remote configs if such checks aren't implemented elsewhere in the codebase.

Applied to files:

  • internal/exec/validate_stacks_test.go
  • internal/exec/stack_processor_utils.go
📚 Learning: 2025-08-15T14:43:41.030Z
Learnt from: aknysh
PR: cloudposse/atmos#1352
File: pkg/store/artifactory_store_test.go:108-113
Timestamp: 2025-08-15T14:43:41.030Z
Learning: In test files for the atmos project, it's acceptable to ignore errors from os.Setenv/Unsetenv operations during test environment setup and teardown, as these are controlled test scenarios.

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2024-10-23T21:36:40.262Z
Learnt from: osterman
PR: cloudposse/atmos#740
File: cmd/cmd_utils.go:340-359
Timestamp: 2024-10-23T21:36:40.262Z
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.

Applied to files:

  • internal/exec/validate_stacks_test.go
  • internal/exec/stack_processor_utils.go
  • pkg/merge/merge_with_context_test.go
📚 Learning: 2024-10-20T00:57:53.500Z
Learnt from: haitham911
PR: cloudposse/atmos#731
File: internal/exec/validate_stacks.go:0-0
Timestamp: 2024-10-20T00:57:53.500Z
Learning: In `internal/exec/validate_stacks.go`, when downloading the Atmos JSON Schema file to the temp directory, the temporary file is overwritten each time, so explicit removal is not necessary.

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2025-07-01T02:22:25.901Z
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*_test.go : Test both happy paths and error conditions

Applied to files:

  • internal/exec/validate_stacks_test.go
  • pkg/merge/merge_with_context_test.go
📚 Learning: 2024-12-07T16:19:01.683Z
Learnt from: aknysh
PR: cloudposse/atmos#825
File: internal/exec/terraform.go:30-30
Timestamp: 2024-12-07T16:19:01.683Z
Learning: In `internal/exec/terraform.go`, skipping stack validation when help flags are present is not necessary.

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2024-11-19T23:00:45.899Z
Learnt from: osterman
PR: cloudposse/atmos#795
File: internal/exec/stack_processor_utils.go:378-386
Timestamp: 2024-11-19T23:00:45.899Z
Learning: In the `ProcessYAMLConfigFile` function within `internal/exec/stack_processor_utils.go`, directory traversal in stack imports is acceptable and should not be restricted.

Applied to files:

  • internal/exec/validate_stacks_test.go
  • internal/exec/stack_processor_utils.go
📚 Learning: 2025-07-01T02:22:25.901Z
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*_test.go : Use test fixtures for complex inputs

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2025-01-09T22:27:25.538Z
Learnt from: samtholiya
PR: cloudposse/atmos#914
File: cmd/validate_stacks.go:20-23
Timestamp: 2025-01-09T22:27:25.538Z
Learning: The validate commands in Atmos can have different help handling implementations. Specifically, validate_component.go and validate_stacks.go are designed to handle help requests differently, with validate_stacks.go including positional argument checks while validate_component.go does not.

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2025-09-07T15:13:17.831Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-07T15:13:17.831Z
Learning: Applies to pkg/utils/yaml_utils.go : Prefer existing YAML processing utilities in pkg/utils/yaml_utils.go before adding new ones.

Applied to files:

  • internal/exec/stack_processor_utils.go
📚 Learning: 2025-04-11T22:06:46.999Z
Learnt from: samtholiya
PR: cloudposse/atmos#1147
File: internal/exec/validate_schema.go:42-57
Timestamp: 2025-04-11T22:06:46.999Z
Learning: The "ExecuteAtmosValidateSchemaCmd" function in internal/exec/validate_schema.go has been reviewed and confirmed to have acceptable cognitive complexity despite static analysis warnings. The function uses a clean structure with only three if statements for error handling and delegates complex operations to helper methods.

Applied to files:

  • internal/exec/stack_processor_utils.go
  • pkg/merge/merge_with_context_test.go
📚 Learning: 2025-09-07T15:13:17.831Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-07T15:13:17.831Z
Learning: Applies to **/*.go : Wrap all returned errors using static errors from the errors package; never return dynamic errors directly.

Applied to files:

  • internal/exec/stack_processor_utils.go
📚 Learning: 2025-09-13T18:06:07.674Z
Learnt from: samtholiya
PR: cloudposse/atmos#1466
File: toolchain/list.go:39-42
Timestamp: 2025-09-13T18:06:07.674Z
Learning: In the cloudposse/atmos repository, for UI messages in the toolchain package, use utils.PrintfMessageToTUI instead of log.Error or fmt.Fprintln(os.Stderr, ...). Import pkg/utils with alias "u" to follow the established pattern.

Applied to files:

  • internal/exec/stack_processor_utils.go
📚 Learning: 2025-09-07T15:13:17.831Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-07T15:13:17.831Z
Learning: Applies to pkg/**/*_test.go : Unit tests reside under pkg/ alongside implementations.

Applied to files:

  • pkg/merge/merge_with_context_test.go
📚 Learning: 2025-07-01T02:22:25.901Z
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*_test.go : Every new feature must include comprehensive unit tests

Applied to files:

  • pkg/merge/merge_with_context_test.go
📚 Learning: 2024-10-19T17:42:29.152Z
Learnt from: Cerebrovinny
PR: cloudposse/atmos#729
File: internal/exec/terraform.go:258-264
Timestamp: 2024-10-19T17:42:29.152Z
Learning: Prefer not to declare variables within 'if' statements in Go code.

Applied to files:

  • pkg/merge/merge_with_context_test.go
🧬 Code graph analysis (3)
internal/exec/validate_stacks_test.go (4)
pkg/schema/schema.go (7)
  • AtmosConfiguration (25-60)
  • Stacks (352-358)
  • Logs (365-368)
  • Components (346-350)
  • Terraform (306-318)
  • Settings (834-838)
  • AtmosSettings (226-246)
internal/exec/validate_stacks.go (1)
  • ValidateStacks (64-244)
internal/exec/stack_processor_utils.go (1)
  • ProcessYAMLConfigFile (160-203)
pkg/stack/stack_processor.go (1)
  • ProcessYAMLConfigFile (38-79)
internal/exec/stack_processor_utils.go (4)
pkg/merge/merge_context.go (2)
  • NewMergeContext (23-27)
  • MergeContext (10-20)
pkg/utils/file_utils.go (1)
  • TrimBasePathFromPath (82-86)
errors/errors.go (1)
  • ErrInvalidStackManifest (82-82)
pkg/merge/merge.go (1)
  • MergeWithContext (113-158)
pkg/merge/merge_with_context_test.go (3)
pkg/schema/schema.go (3)
  • AtmosConfiguration (25-60)
  • Settings (834-838)
  • AtmosSettings (226-246)
pkg/merge/merge_context.go (1)
  • NewMergeContext (23-27)
pkg/merge/merge.go (1)
  • MergeWithContext (113-158)
⏰ 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). (6)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Build (macos-latest, macos)
  • GitHub Check: Build (ubuntu-latest, linux)
  • GitHub Check: Lint (golangci)
  • GitHub Check: Analyze (go)
  • GitHub Check: Summary
🔇 Additional comments (5)
internal/exec/validate_stacks_test.go (3)

22-40: Make the test deterministic: set the list merge strategy.

Type-mismatch behavior can vary by strategy. Set Settings.ListMergeStrategy explicitly.

   atmosConfig := &schema.AtmosConfiguration{
     BasePath:               absPath,
     StacksBaseAbsolutePath: filepath.Join(absPath, "stacks"),
+    Settings: schema.AtmosSettings{
+      ListMergeStrategy: "replace",
+    },
     Stacks: schema.Stacks{

78-99: Exercise the context-aware API you intend to validate.

Call ProcessYAMLConfigFileWithContext and pass a fresh merge context.

+ m "github.com/cloudposse/atmos/pkg/merge"
@@
-  _, _, _, _, _, _, _, err = ProcessYAMLConfigFile( //nolint:dogsled
+  _, _, _, _, _, _, _, err = ProcessYAMLConfigFileWithContext( //nolint:dogsled
      atmosConfig,
      basePath,
      filePath,
      importsConfig,
      map[string]any{},
      false, // ignoreMissingFiles
      false, // skipTemplatesProcessingInImports
      false, // ignoreMissingTemplateValues
      false, // skipIfMissing
      map[string]any{},
      map[string]any{},
      map[string]any{},
      map[string]any{},
-     "", // atmosManifestJsonSchemaFilePath
-  )
+     "", // atmosManifestJsonSchemaFilePath
+     m.NewMergeContext(),
+  )

Also applies to: 101-117


47-75: Promote warnings to assertions and verify dedup/context tokens.

Fail fast on regressions; assert error presence, core message, no duplicates, and context markers.

-    err := ValidateStacks(atmosConfig)
-
-    if err != nil {
-      errStr := err.Error()
-      // Check that the error contains merge context information
-      // The error should mention the files involved
-      assert.Contains(t, errStr, "cannot override two slices with different type", "Should contain the original merge error")
-      // Since we're using MergeContext, we should see file information
-      // Note: The exact format depends on how the error propagates through the system
-      if strings.Contains(errStr, "File being processed:") ||
-        strings.Contains(errStr, "Import chain:") ||
-        strings.Contains(errStr, "base.yaml") ||
-        strings.Contains(errStr, "override.yaml") ||
-        strings.Contains(errStr, "test-environment.yaml") {
-        // Good - we have context information
-        t.Logf("Error contains context information: %s", errStr)
-      } else {
-        t.Logf("Warning: Error might not contain full context. Error: %s", errStr)
-      }
-    } else {
-      // If validation passes when it shouldn't, that's also useful to know
-      t.Log("Validation passed - type mismatch might not be triggered with current merge strategy")
-    }
+    err := ValidateStacks(atmosConfig)
+    assert.Error(t, err, "validate should fail on type mismatch.")
+    errStr := err.Error()
+    assert.Contains(t, errStr, "cannot override two slices with different type")
+    assert.Equal(t, 1, strings.Count(errStr, "cannot override two slices with different type"), "should not duplicate merge errors.")
+    assert.Contains(t, errStr, "File being processed:")
+    assert.Contains(t, errStr, "Import chain:")
+    assert.True(t,
+      strings.Contains(errStr, "base.yaml") ||
+        strings.Contains(errStr, "override.yaml") ||
+        strings.Contains(errStr, "test-environment.yaml"),
+      "should reference at least one file involved.")
internal/exec/stack_processor_utils.go (2)

185-203: Wrapper for backward-compatibility looks good.

Delegation preserves old API while enabling context internally.


77-93: Approve: MergeContext threaded; no direct stderr prints in merge paths

Verified — no production code in pkg/merge writes directly to os.Stderr. Matches are test captures and intentional stderr usages: internal/exec/vendor_utils.go (StderrLogger = log.New(os.Stderr)), internal/exec/shell_utils.go (cmd.Stderr = os.Stderr), and tests in pkg/merge that capture stderr.

Comment thread errors/errors.go Resolved
- Set explicit ListMergeStrategy in test config to avoid flaky behavior
- Convert test warnings to assertions for better failure detection
- Add deduplication checks for error context tokens (max 5 occurrences)
- Populate expectedParts with meaningful tokens for validation tests
- Fix FormatError to properly wrap errors, preserving sentinel errors for errors.Is()
- Update call sites to wrap with ErrInvalidStackManifest before formatting
- Ensure error chain is preserved throughout the validation pipeline

These changes make tests more deterministic and improve error diagnostics while
maintaining backward compatibility with error detection patterns.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
coderabbitai[bot]
coderabbitai Bot previously approved these changes Sep 22, 2025
Comment thread pkg/merge/merge_context.go Fixed
autofix-ci Bot and others added 3 commits September 22, 2025 23:42
- Added explanatory comments to all //nolint directives explaining why they're needed
- Fixed string concatenation in terraform_plan_diff_formatting.go to use fmt.Sprintf
- Documented that log.Fatal is appropriate for version display errors
- Documented that FormatError's complexity is necessary for detailed error formatting

These changes make the codebase more maintainable by clearly documenting
why certain linter suppressions are necessary, and improve code quality
by using idiomatic Go patterns.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (8)
internal/exec/validate_stacks.go (3)

156-160: Drop unused accumulator or put it to use.

allImportsConfig is written but never read. Remove it (and related writes) to reduce noise and allocations.

-	// Track imported files to avoid processing them at the top level
-	// This ensures we see the full import chain in error messages
-	importedFiles := make(map[string]bool)
-	allImportsConfig := make(map[string]map[string]any)
+	// Track imported files to avoid processing them at the top level.
+	// This ensures we see the full import chain in error messages.
+	importedFiles := make(map[string]bool)

161-185: First pass can miss templated imports; make it tolerant and normalize paths.

To better discover imports without spurious failures:

  • Use the context-aware API (even if you ignore the error) for consistency.
  • Set ignoreMissingTemplateValues=true and skipIfMissing=true.
  • Normalize keys with filepath.ToSlash to avoid OS-specific mismatches.
-	// First pass: identify all imported files
+	// First pass: identify all imported files.
 	for _, filePath := range stackConfigFilesAbsolutePaths {
-		_, importsConfig, _, _, _, _, _, _ := ProcessYAMLConfigFile(
+		_, importsConfig, _, _, _, _, _, _ := ProcessYAMLConfigFileWithContext(
 			atmosConfig,
 			atmosConfig.StacksBaseAbsolutePath,
 			filePath,
 			map[string]map[string]any{},
 			nil,
-			true, // ignoreMissingFiles for first pass
-			false,
-			false,
-			false,
+			true,  // ignoreMissingFiles for first pass
+			false, // skipTemplatesProcessingInImports
+			true,  // ignoreMissingTemplateValues (tolerate unresolved tmpl vars)
+			true,  // skipIfMissing (glob/templates may not resolve here)
 			map[string]any{},
 			map[string]any{},
 			map[string]any{},
 			map[string]any{},
 			atmosManifestJsonSchemaFilePath,
+			m.NewMergeContext(),
 		)
 
-		// Track all imported files
+		// Track all imported files.
 		for importPath := range importsConfig {
-			importedFiles[importPath] = true
-			allImportsConfig[importPath] = importsConfig[importPath]
+			importedFiles[filepath.ToSlash(importPath)] = true
 		}
 	}

187-203: Path handling is mostly normalized; minor hardening.

TrimBasePathFromPath already ToSlash-es, but consider ToSlash-ing relativeFilePathNoExt before lookup to fully align with first-pass keys.

 		ext := filepath.Ext(relativeFilePath)
 		if ext != "" {
 			relativeFilePathNoExt = strings.TrimSuffix(relativeFilePath, ext)
 		}
+		relativeFilePathNoExt = filepath.ToSlash(relativeFilePathNoExt)
pkg/merge/merge_context.go (3)

29-42: Normalize paths when appending to the chain.

To keep output stable across platforms and call sites, convert filePath to slash-separated once here.

 func (mc *MergeContext) WithFile(filePath string) *MergeContext {
+	filePath = strings.ReplaceAll(filePath, "\\", "/")
 	if mc == nil {
 		mc = NewMergeContext()
 	}

57-125: Preserves sentinel errors. Consider splitting to reduce complexity and lints.

Great: %w keeps errors.Is working. Function length/complexity and repeated strings may trip linters; extract helpers.

-// FormatError formats an error with merge context information.
-//
-//nolint:revive
-func (mc *MergeContext) FormatError(err error, additionalInfo ...string) error {
+// FormatError formats an error with merge context information.
+func (mc *MergeContext) FormatError(err error, additionalInfo ...string) error {
 	if err == nil {
 		return nil
 	}
 
 	if mc == nil || (mc.CurrentFile == "" && len(mc.ImportChain) == 0) {
 		// No context available, return original error unchanged
 		return err
 	}
 
-	var sb strings.Builder
-
-	// Build the context information (without including the error message itself)
-	sb.WriteString("\n\n```\n")
-	// Add current file being processed
-	if mc.CurrentFile != "" {
-		sb.WriteString(fmt.Sprintf("File being processed: %s", mc.CurrentFile))
-	}
-	// Add import chain if available
-	if len(mc.ImportChain) > 0 {
-		sb.WriteString("\nImport chain:")
-		for i, file := range mc.ImportChain {
-			var indent string
-			if i == 0 {
-				indent = "\n  → "
-			} else {
-				// Add proper indentation for nested imports
-				indent = "\n    → "
-			}
-			sb.WriteString(fmt.Sprintf("%s%s", indent, file))
-		}
-	}
-	// Add any additional information
-	if len(additionalInfo) > 0 {
-		for _, info := range additionalInfo {
-			if info != "" {
-				sb.WriteString("\n")
-				sb.WriteString(info)
-			}
-		}
-	}
-	// Close the code fence
-	sb.WriteString("\n```")
-
-	// Add helpful hints for common merge errors
-	errStr := err.Error()
-	if strings.Contains(errStr, "cannot override two slices with different type") {
-		sb.WriteString("\n\n**Likely cause:** A key is defined as an array in one file and as a string in another.")
-		sb.WriteString("\n\n**Debug hint:** Check the files above for keys that have different types.")
-		sb.WriteString("\n\n**Common issues:**")
-		sb.WriteString("\n- `vars` defined as both array and string")
-		sb.WriteString("\n- `settings` with inconsistent types across imports")
-		sb.WriteString("\n- `overrides` attempting to change field types")
-	} else if strings.Contains(errStr, "cannot override") {
-		sb.WriteString("\n\n**Likely cause:** Type mismatch when merging configurations.")
-		sb.WriteString("\n\n**Debug hint:** Ensure consistent types for the same keys across all files.")
-	}
-
-	// Wrap the original error to preserve the error chain
-	// This allows errors.Is() to work with sentinel errors
-	return fmt.Errorf("%w%s", err, sb.String())
+	ctx := mc.buildContextBlock(additionalInfo...)
+	hints := buildHints(err.Error())
+	return fmt.Errorf("%w%s%s", err, ctx, hints)
 }
+
+// buildContextBlock constructs a fenced context block with file and import chain.
+func (mc *MergeContext) buildContextBlock(additionalInfo ...string) string {
+	var b strings.Builder
+	b.WriteString("\n\n```\n")
+	if mc.CurrentFile != "" {
+		b.WriteString("File being processed: ")
+		b.WriteString(mc.CurrentFile)
+	}
+	if n := len(mc.ImportChain); n > 0 {
+		b.WriteString("\nImport chain:")
+		for i, f := range mc.ImportChain {
+			if i == 0 {
+				b.WriteString("\n  → ")
+			} else {
+				b.WriteString("\n    → ")
+			}
+			b.WriteString(f)
+		}
+	}
+	for _, info := range additionalInfo {
+		if info != "" {
+			b.WriteString("\n")
+			b.WriteString(info)
+		}
+	}
+	b.WriteString("\n```")
+	return b.String()
+}
+
+// buildHints appends heuristic guidance for common merge failures.
+func buildHints(msg string) string {
+	if strings.Contains(msg, "cannot override two slices with different type") {
+		return "\n\n**Likely cause:** A key is defined as an array in one file and as a string in another." +
+			"\n\n**Debug hint:** Check the files above for keys that have different types." +
+			"\n\n**Common issues:**" +
+			"\n- `vars` defined as both array and string" +
+			"\n- `settings` with inconsistent types across imports" +
+			"\n- `overrides` attempting to change field types"
+	}
+	if strings.Contains(msg, "cannot override") {
+		return "\n\n**Likely cause:** Type mismatch when merging configurations." +
+			"\n\n**Debug hint:** Ensure consistent types for the same keys across all files."
+	}
+	return ""
+}

144-157: Optional: speed up membership test for long chains.

For deep chains, a small set built once per call could reduce linear scans. Likely not hot; fine to defer.

internal/exec/validate_stacks_test.go (2)

50-99: Tighten assertions slightly.

You can replace the NotNil+Fatal combo with require.Error(t, err) to fail fast and simplify.

-		assert.NotNil(t, err, "Expected validation to fail with type mismatch error")
-		if err == nil {
-			t.Fatal("Expected validation to fail but it passed")
-		}
+		require.Error(t, err, "Expected validation to fail with type mismatch error.")

158-224: Token-based assertions are reasonable; consider require.Error for early exit.

Keeps the test resilient; switching to require.Error (as above) would simplify control flow.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 78f79d4 and f455e41.

📒 Files selected for processing (3)
  • internal/exec/validate_stacks.go (3 hunks)
  • internal/exec/validate_stacks_test.go (1 hunks)
  • pkg/merge/merge_context.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*.go: Use Viper for managing configuration, environment variables, and flags
Use interfaces for external dependencies to facilitate mocking
All code must pass golangci-lint checks
Follow Go's error handling idioms
Use meaningful error messages
Wrap errors with context using fmt.Errorf("context: %w", err)
Consider using a custom error type for domain-specific errors
Follow standard Go coding style
Use gofmt and goimports to format code
Prefer short, descriptive variable names
Use snake_case for environment variables
Document all exported functions, types, and methods
Document complex logic with inline comments
Follow Go's documentation conventions
Use Viper for configuration management
Support configuration via files, environment variables, and flags
Follow the precedence order: flags > environment variables > config file > defaults

**/*.go: All comments in Go code must end with periods (enforced by golangci-lint godot).
Wrap all returned errors using static errors from the errors package; never return dynamic errors directly.
Always bind environment variables with viper.BindEnv() and provide ATMOS_ alternatives for each external var.
Separate structured logging from UI output: use stderr for prompts/errors to user; stdout only for data; never use logging for UI.
Most text UI must go to stderr; only data/results to stdout. Prefer utils.PrintfMessageToTUI for UI messages.
For non-standard execution paths, capture telemetry with telemetry.CaptureCmd or telemetry.CaptureCmdString and never capture user data.
Ensure cross-platform compatibility: prefer SDKs to external binaries, use filepath/os/runtime for portability, and add build constraints when needed.

Files:

  • internal/exec/validate_stacks_test.go
  • pkg/merge/merge_context.go
  • internal/exec/validate_stacks.go
**/*_test.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*_test.go: Every new feature must include comprehensive unit tests
Test both happy paths and error conditions
Use table-driven tests for testing multiple scenarios
Include integration tests for command flows
Test CLI end-to-end when possible
Use test fixtures for complex inputs
Consider using testify/mock for creating mock implementations

**/*_test.go: Always use t.Skipf() with a reason for skipped tests; never use t.Skip() or reasonless t.Skipf().
Test files must mirror implementation structure and naming (e.g., aws_ssm_store_test.go).
Use table-driven unit tests and mock interfaces for external dependencies; target >80% coverage.

Files:

  • internal/exec/validate_stacks_test.go
🧠 Learnings (26)
📓 Common learnings
Learnt from: Listener430
PR: cloudposse/atmos#934
File: tests/fixtures/scenarios/docs-generate/README.md.gotmpl:99-118
Timestamp: 2025-01-25T03:51:57.689Z
Learning: For the cloudposse/atmos repository, changes to template contents should be handled in dedicated PRs and are typically considered out of scope for PRs focused on other objectives.
📚 Learning: 2024-11-13T21:37:07.852Z
Learnt from: Cerebrovinny
PR: cloudposse/atmos#764
File: internal/exec/describe_stacks.go:289-295
Timestamp: 2024-11-13T21:37:07.852Z
Learning: In the `internal/exec/describe_stacks.go` file of the `atmos` project written in Go, avoid extracting the stack name handling logic into a helper function within the `ExecuteDescribeStacks` method, even if the logic appears duplicated.

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2025-09-07T15:13:17.831Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-07T15:13:17.831Z
Learning: Applies to internal/exec/stack_processor_utils.go : Stack processing utilities should reside here; test multiple inheritance scenarios.

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2024-10-20T00:41:57.135Z
Learnt from: haitham911
PR: cloudposse/atmos#731
File: internal/exec/validate_stacks.go:93-98
Timestamp: 2024-10-20T00:41:57.135Z
Learning: When downloading schema files in `internal/exec/validate_stacks.go`, use a consistent temporary file name to overwrite the file each time and avoid creating multiple temporary files.

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2024-12-07T16:16:13.038Z
Learnt from: Listener430
PR: cloudposse/atmos#825
File: internal/exec/helmfile_generate_varfile.go:28-31
Timestamp: 2024-12-07T16:16:13.038Z
Learning: In `internal/exec/helmfile_generate_varfile.go`, the `--help` command (`./atmos helmfile generate varfile --help`) works correctly without requiring stack configurations, and the only change needed was to make `ProcessCommandLineArgs` exportable by capitalizing its name.

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2024-12-12T15:17:45.245Z
Learnt from: osterman
PR: cloudposse/atmos#808
File: examples/demo-atmos.d/atmos.d/tools/helmfile.yml:10-10
Timestamp: 2024-12-12T15:17:45.245Z
Learning: In `examples/demo-atmos.d/atmos.d/tools/helmfile.yml`, when suggesting changes to `kubeconfig_path`, ensure that the values use valid Go template syntax.

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2025-03-18T12:26:25.329Z
Learnt from: Listener430
PR: cloudposse/atmos#1149
File: tests/snapshots/TestCLICommands_atmos_vendor_pull_ssh.stderr.golden:7-7
Timestamp: 2025-03-18T12:26:25.329Z
Learning: In the Atmos project, typos or inconsistencies in test snapshot files (such as "terrafrom" instead of "terraform") may be intentional as they capture the exact output of commands and should not be flagged as issues requiring correction.

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2024-12-02T21:26:32.337Z
Learnt from: osterman
PR: cloudposse/atmos#808
File: pkg/config/config.go:478-483
Timestamp: 2024-12-02T21:26:32.337Z
Learning: In the 'atmos' project, when reviewing Go code like `pkg/config/config.go`, avoid suggesting file size checks after downloading remote configs if such checks aren't implemented elsewhere in the codebase.

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2025-08-15T14:43:41.030Z
Learnt from: aknysh
PR: cloudposse/atmos#1352
File: pkg/store/artifactory_store_test.go:108-113
Timestamp: 2025-08-15T14:43:41.030Z
Learning: In test files for the atmos project, it's acceptable to ignore errors from os.Setenv/Unsetenv operations during test environment setup and teardown, as these are controlled test scenarios.

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2024-10-23T21:36:40.262Z
Learnt from: osterman
PR: cloudposse/atmos#740
File: cmd/cmd_utils.go:340-359
Timestamp: 2024-10-23T21:36:40.262Z
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.

Applied to files:

  • internal/exec/validate_stacks_test.go
  • pkg/merge/merge_context.go
📚 Learning: 2025-07-01T02:22:25.901Z
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*_test.go : Test both happy paths and error conditions

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2024-12-07T16:19:01.683Z
Learnt from: aknysh
PR: cloudposse/atmos#825
File: internal/exec/terraform.go:30-30
Timestamp: 2024-12-07T16:19:01.683Z
Learning: In `internal/exec/terraform.go`, skipping stack validation when help flags are present is not necessary.

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2024-11-19T23:00:45.899Z
Learnt from: osterman
PR: cloudposse/atmos#795
File: internal/exec/stack_processor_utils.go:378-386
Timestamp: 2024-11-19T23:00:45.899Z
Learning: In the `ProcessYAMLConfigFile` function within `internal/exec/stack_processor_utils.go`, directory traversal in stack imports is acceptable and should not be restricted.

Applied to files:

  • internal/exec/validate_stacks_test.go
  • internal/exec/validate_stacks.go
📚 Learning: 2025-07-01T02:22:25.901Z
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*_test.go : Use test fixtures for complex inputs

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2025-01-09T22:27:25.538Z
Learnt from: samtholiya
PR: cloudposse/atmos#914
File: cmd/validate_stacks.go:20-23
Timestamp: 2025-01-09T22:27:25.538Z
Learning: The validate commands in Atmos can have different help handling implementations. Specifically, validate_component.go and validate_stacks.go are designed to handle help requests differently, with validate_stacks.go including positional argument checks while validate_component.go does not.

Applied to files:

  • internal/exec/validate_stacks_test.go
📚 Learning: 2025-07-01T02:22:25.901Z
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*.go : Wrap errors with context using `fmt.Errorf("context: %w", err)`

Applied to files:

  • pkg/merge/merge_context.go
📚 Learning: 2025-09-10T22:38:42.212Z
Learnt from: Benbentwo
PR: cloudposse/atmos#1475
File: pkg/auth/identities/aws/user.go:141-145
Timestamp: 2025-09-10T22:38:42.212Z
Learning: The user confirmed that the errors package has an error string wrapping format, contradicting the previous learning about ErrWrappingFormat being invalid. The current usage of fmt.Errorf(errUtils.ErrWrappingFormat, errUtils.ErrAuthAwsFileManagerFailed, err) appears to be the correct pattern.

Applied to files:

  • pkg/merge/merge_context.go
📚 Learning: 2025-04-11T22:06:46.999Z
Learnt from: samtholiya
PR: cloudposse/atmos#1147
File: internal/exec/validate_schema.go:42-57
Timestamp: 2025-04-11T22:06:46.999Z
Learning: The "ExecuteAtmosValidateSchemaCmd" function in internal/exec/validate_schema.go has been reviewed and confirmed to have acceptable cognitive complexity despite static analysis warnings. The function uses a clean structure with only three if statements for error handling and delegates complex operations to helper methods.

Applied to files:

  • pkg/merge/merge_context.go
📚 Learning: 2025-09-07T15:13:17.831Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-07T15:13:17.831Z
Learning: Applies to **/*.go : Wrap all returned errors using static errors from the errors package; never return dynamic errors directly.

Applied to files:

  • pkg/merge/merge_context.go
📚 Learning: 2025-09-07T15:13:17.831Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-07T15:13:17.831Z
Learning: Applies to errors/errors.go : Define all static errors in errors/errors.go.

Applied to files:

  • pkg/merge/merge_context.go
📚 Learning: 2025-04-04T02:03:23.676Z
Learnt from: aknysh
PR: cloudposse/atmos#1185
File: internal/exec/yaml_func_store.go:26-26
Timestamp: 2025-04-04T02:03:23.676Z
Learning: The Atmos codebase currently uses `log.Fatal` for error handling in multiple places. The maintainers are aware this isn't an ideal pattern (should only be used in main() or init() functions) and plan to address it comprehensively in a separate PR. CodeRabbit should not flag these issues or push for immediate changes until that refactoring is complete.

Applied to files:

  • pkg/merge/merge_context.go
📚 Learning: 2025-09-13T18:06:07.674Z
Learnt from: samtholiya
PR: cloudposse/atmos#1466
File: toolchain/list.go:39-42
Timestamp: 2025-09-13T18:06:07.674Z
Learning: In the cloudposse/atmos repository, for UI messages in the toolchain package, use utils.PrintfMessageToTUI instead of log.Error or fmt.Fprintln(os.Stderr, ...). Import pkg/utils with alias "u" to follow the established pattern.

Applied to files:

  • pkg/merge/merge_context.go
📚 Learning: 2025-07-01T02:22:25.901Z
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*.go : Consider using a custom error type for domain-specific errors

Applied to files:

  • pkg/merge/merge_context.go
📚 Learning: 2025-09-10T22:38:42.212Z
Learnt from: Benbentwo
PR: cloudposse/atmos#1475
File: pkg/auth/identities/aws/user.go:141-145
Timestamp: 2025-09-10T22:38:42.212Z
Learning: ErrWrappingFormat is correctly defined as "%w: %w" in the errors package and is used throughout the codebase to wrap two error types together. The usage fmt.Errorf(errUtils.ErrWrappingFormat, errUtils.ErrAuthAwsFileManagerFailed, err) is the correct pattern when both arguments are error types.

Applied to files:

  • pkg/merge/merge_context.go
📚 Learning: 2025-09-07T15:13:17.831Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-07T15:13:17.831Z
Learning: Applies to pkg/stack/** : Make stack processing changes in pkg/stack/ and validate inheritance/template rendering.

Applied to files:

  • internal/exec/validate_stacks.go
📚 Learning: 2025-07-05T20:59:02.914Z
Learnt from: aknysh
PR: cloudposse/atmos#1363
File: internal/exec/template_utils.go:18-18
Timestamp: 2025-07-05T20:59:02.914Z
Learning: In the Atmos project, gomplate v4 is imported with a blank import (`_ "github.com/hairyhenderson/gomplate/v4"`) alongside v3 imports to resolve AWS SDK version conflicts. V3 uses older AWS SDK versions that conflict with newer AWS modules used by Atmos. A full migration to v4 requires extensive refactoring due to API changes and should be handled in a separate PR.

Applied to files:

  • internal/exec/validate_stacks.go
🧬 Code graph analysis (2)
internal/exec/validate_stacks_test.go (4)
pkg/schema/schema.go (7)
  • AtmosConfiguration (25-60)
  • Stacks (353-359)
  • Logs (366-369)
  • Components (347-351)
  • Terraform (307-319)
  • Settings (835-839)
  • AtmosSettings (226-246)
internal/exec/validate_stacks.go (1)
  • ValidateStacks (65-256)
internal/exec/stack_processor_utils.go (1)
  • ProcessYAMLConfigFile (160-203)
pkg/stack/stack_processor.go (1)
  • ProcessYAMLConfigFile (38-79)
internal/exec/validate_stacks.go (3)
internal/exec/stack_processor_utils.go (2)
  • ProcessYAMLConfigFile (160-203)
  • ProcessYAMLConfigFileWithContext (210-647)
pkg/utils/file_utils.go (1)
  • TrimBasePathFromPath (82-86)
pkg/merge/merge_context.go (1)
  • NewMergeContext (23-27)
⏰ 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). (5)
  • GitHub Check: Build (ubuntu-latest, linux)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Lint (golangci)
  • GitHub Check: Analyze (go)
  • GitHub Check: Summary
🔇 Additional comments (7)
internal/exec/validate_stacks.go (3)

19-19: Importing merge package looks good.

Needed for context-aware processing; no concerns.


224-248: Good: single-source of truth for errors and no duplicate reporting.

Collecting YAML errors first, then processing stacks only on success, avoids duplicate noise and aligns with the PR goals.


204-223: Resolved — callee already records the top-level file

ProcessYAMLConfigFileWithContext calls mergeContext = mergeContext.WithFile(relativeFilePath) unconditionally, so adding WithFile(relativeFilePath) here is unnecessary (see internal/exec/stack_processor_utils.go:243).

pkg/merge/merge_context.go (2)

22-27: Constructor is clear and documented.

No issues.


127-134: Helper is fine as-is.

No action needed.

internal/exec/validate_stacks_test.go (2)

14-43: Solid test scaffold; deterministic merge strategy is a good call.

Config and debug logging setup look good.


101-156: Exercise the context-aware API in this context test.

This test discusses import-chain tracking but calls the non-context wrapper. Call ProcessYAMLConfigFileWithContext and pass a merge context.

@@
-import (
-	"path/filepath"
-	"strings"
-	"testing"
-
-	"github.com/stretchr/testify/assert"
-
-	"github.com/cloudposse/atmos/pkg/schema"
-	u "github.com/cloudposse/atmos/pkg/utils"
-)
+import (
+	"path/filepath"
+	"strings"
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+
+	m "github.com/cloudposse/atmos/pkg/merge"
+	"github.com/cloudposse/atmos/pkg/schema"
+	u "github.com/cloudposse/atmos/pkg/utils"
+)
@@
-	_, _, _, _, _, _, _, err = ProcessYAMLConfigFile( //nolint:dogsled
+	_, _, _, _, _, _, _, err = ProcessYAMLConfigFileWithContext( //nolint:dogsled
 		atmosConfig,
 		basePath,
 		filePath,
 		importsConfig,
 		map[string]any{},
 		false, // ignoreMissingFiles
 		false, // skipTemplatesProcessingInImports
 		false, // ignoreMissingTemplateValues
 		false, // skipIfMissing
 		map[string]any{},
 		map[string]any{},
 		map[string]any{},
 		map[string]any{},
-		"", // atmosManifestJsonSchemaFilePath
-	)
+		"", // atmosManifestJsonSchemaFilePath
+		m.NewMergeContext(),
+	)

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (3)
pkg/merge/merge_context.go (3)

60-125: Refactor FormatError to reduce complexity/length and drop nolint.

Split rendering into helpers; also simplifies import-chain output and removes the revive/function-length warnings.

-//nolint:revive // cognitive-complexity: detailed error formatting requires multiple conditions
 func (mc *MergeContext) FormatError(err error, additionalInfo ...string) error {
@@
-	var sb strings.Builder
-
-	// Build the context information (without including the error message itself)
-	sb.WriteString("\n\n```\n")
-	// Add current file being processed
-	if mc.CurrentFile != "" {
-		sb.WriteString(fmt.Sprintf("File being processed: %s", mc.CurrentFile))
-	}
-	// Add import chain if available
-	if len(mc.ImportChain) > 0 {
-		sb.WriteString("\nImport chain:")
-		for i, file := range mc.ImportChain {
-			var indent string
-			if i == 0 {
-				indent = "\n  → "
-			} else {
-				// Add proper indentation for nested imports
-				indent = "\n    → "
-			}
-			sb.WriteString(fmt.Sprintf("%s%s", indent, file))
-		}
-	}
-	// Add any additional information
-	if len(additionalInfo) > 0 {
-		for _, info := range additionalInfo {
-			if info != "" {
-				sb.WriteString("\n")
-				sb.WriteString(info)
-			}
-		}
-	}
-	// Close the code fence
-	sb.WriteString("\n```")
-
-	// Add helpful hints for common merge errors
-	errStr := err.Error()
-	if strings.Contains(errStr, "cannot override two slices with different type") {
-		sb.WriteString("\n\n**Likely cause:** A key is defined as an array in one file and as a string in another.")
-		sb.WriteString("\n\n**Debug hint:** Check the files above for keys that have different types.")
-		sb.WriteString("\n\n**Common issues:**")
-		sb.WriteString("\n- `vars` defined as both array and string")
-		sb.WriteString("\n- `settings` with inconsistent types across imports")
-		sb.WriteString("\n- `overrides` attempting to change field types")
-	} else if strings.Contains(errStr, "cannot override") {
-		sb.WriteString("\n\n**Likely cause:** Type mismatch when merging configurations.")
-		sb.WriteString("\n\n**Debug hint:** Ensure consistent types for the same keys across all files.")
-	}
-
-	// Wrap the original error to preserve the error chain
-	// This allows errors.Is() to work with sentinel errors
-	return fmt.Errorf("%w%s", err, sb.String())
+	ctx := mc.buildContextBlock(additionalInfo)
+	hints := buildMergeHints(err.Error())
+	return fmt.Errorf("%w%s%s", err, ctx, hints)
 }

Add these helpers in the same file (outside the selected range):

// buildContextBlock renders file/import chain plus optional info as a fenced block.
func (mc *MergeContext) buildContextBlock(additionalInfo []string) string {
	var sb strings.Builder
	sb.WriteString("\n\n```\n")
	if mc.CurrentFile != "" {
		sb.WriteString("File being processed: ")
		sb.WriteString(mc.CurrentFile)
	}
	if len(mc.ImportChain) > 0 {
		sb.WriteString("\nImport chain:\n  → ")
		sb.WriteString(strings.Join(mc.ImportChain, "\n    → "))
	}
	for _, info := range additionalInfo {
		if info != "" {
			sb.WriteString("\n")
			sb.WriteString(info)
		}
	}
	sb.WriteString("\n```")
	return sb.String()
}

// buildMergeHints returns human hints based on the base error text.
func buildMergeHints(errStr string) string {
	var sb strings.Builder
	if strings.Contains(errStr, "cannot override two slices with different type") {
		sb.WriteString("\n\n**Likely cause:** A key is defined as an array in one file and as a string in another.")
		sb.WriteString("\n\n**Debug hint:** Check the files above for keys that have different types.")
		sb.WriteString("\n\n**Common issues:**")
		sb.WriteString("\n- `vars` defined as both array and string")
		sb.WriteString("\n- `settings` with inconsistent types across imports")
		sb.WriteString("\n- `overrides` attempting to change field types")
	} else if strings.Contains(errStr, "cannot override") {
		sb.WriteString("\n\n**Likely cause:** Type mismatch when merging configurations.")
		sb.WriteString("\n\n**Debug hint:** Ensure consistent types for the same keys across all files.")
	}
	return sb.String()
}

81-93: Optional: simplify import-chain rendering.

Join with a single write; reduces branches and future “ineffectual assignment” risks.

-	if len(mc.ImportChain) > 0 {
-		sb.WriteString("\nImport chain:")
-		for i, file := range mc.ImportChain {
-			var indent string
-			if i == 0 {
-				indent = "\n  → "
-			} else {
-				// Add proper indentation for nested imports
-				indent = "\n    → "
-			}
-			sb.WriteString(fmt.Sprintf("%s%s", indent, file))
-		}
-	}
+	if len(mc.ImportChain) > 0 {
+		sb.WriteString("\nImport chain:\n  → ")
+		sb.WriteString(strings.Join(mc.ImportChain, "\n    → "))
+	}

57-125: Optional: consider a domain error type.

A MergeError struct (CurrentFile, ImportChain, Cause error) would enable structured handling while preserving sentinels via Unwrap. Non‑blocking.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between f455e41 and d07a548.

📒 Files selected for processing (3)
  • internal/exec/terraform_plan_diff_formatting.go (1 hunks)
  • internal/exec/version.go (1 hunks)
  • pkg/merge/merge_context.go (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • internal/exec/terraform_plan_diff_formatting.go
  • internal/exec/version.go
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*.go: Use Viper for managing configuration, environment variables, and flags
Use interfaces for external dependencies to facilitate mocking
All code must pass golangci-lint checks
Follow Go's error handling idioms
Use meaningful error messages
Wrap errors with context using fmt.Errorf("context: %w", err)
Consider using a custom error type for domain-specific errors
Follow standard Go coding style
Use gofmt and goimports to format code
Prefer short, descriptive variable names
Use snake_case for environment variables
Document all exported functions, types, and methods
Document complex logic with inline comments
Follow Go's documentation conventions
Use Viper for configuration management
Support configuration via files, environment variables, and flags
Follow the precedence order: flags > environment variables > config file > defaults

**/*.go: All comments in Go code must end with periods (enforced by golangci-lint godot).
Wrap all returned errors using static errors from the errors package; never return dynamic errors directly.
Always bind environment variables with viper.BindEnv() and provide ATMOS_ alternatives for each external var.
Separate structured logging from UI output: use stderr for prompts/errors to user; stdout only for data; never use logging for UI.
Most text UI must go to stderr; only data/results to stdout. Prefer utils.PrintfMessageToTUI for UI messages.
For non-standard execution paths, capture telemetry with telemetry.CaptureCmd or telemetry.CaptureCmdString and never capture user data.
Ensure cross-platform compatibility: prefer SDKs to external binaries, use filepath/os/runtime for portability, and add build constraints when needed.

Files:

  • pkg/merge/merge_context.go
🧠 Learnings (11)
📓 Common learnings
Learnt from: Listener430
PR: cloudposse/atmos#934
File: tests/fixtures/scenarios/docs-generate/README.md.gotmpl:99-118
Timestamp: 2025-01-25T03:51:57.689Z
Learning: For the cloudposse/atmos repository, changes to template contents should be handled in dedicated PRs and are typically considered out of scope for PRs focused on other objectives.
📚 Learning: 2025-07-01T02:22:25.901Z
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*.go : Wrap errors with context using `fmt.Errorf("context: %w", err)`

Applied to files:

  • pkg/merge/merge_context.go
📚 Learning: 2025-09-10T22:38:42.212Z
Learnt from: Benbentwo
PR: cloudposse/atmos#1475
File: pkg/auth/identities/aws/user.go:141-145
Timestamp: 2025-09-10T22:38:42.212Z
Learning: The user confirmed that the errors package has an error string wrapping format, contradicting the previous learning about ErrWrappingFormat being invalid. The current usage of fmt.Errorf(errUtils.ErrWrappingFormat, errUtils.ErrAuthAwsFileManagerFailed, err) appears to be the correct pattern.

Applied to files:

  • pkg/merge/merge_context.go
📚 Learning: 2025-04-11T22:06:46.999Z
Learnt from: samtholiya
PR: cloudposse/atmos#1147
File: internal/exec/validate_schema.go:42-57
Timestamp: 2025-04-11T22:06:46.999Z
Learning: The "ExecuteAtmosValidateSchemaCmd" function in internal/exec/validate_schema.go has been reviewed and confirmed to have acceptable cognitive complexity despite static analysis warnings. The function uses a clean structure with only three if statements for error handling and delegates complex operations to helper methods.

Applied to files:

  • pkg/merge/merge_context.go
📚 Learning: 2024-10-23T21:36:40.262Z
Learnt from: osterman
PR: cloudposse/atmos#740
File: cmd/cmd_utils.go:340-359
Timestamp: 2024-10-23T21:36:40.262Z
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.

Applied to files:

  • pkg/merge/merge_context.go
📚 Learning: 2025-09-07T15:13:17.831Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-07T15:13:17.831Z
Learning: Applies to **/*.go : Wrap all returned errors using static errors from the errors package; never return dynamic errors directly.

Applied to files:

  • pkg/merge/merge_context.go
📚 Learning: 2025-09-07T15:13:17.831Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-07T15:13:17.831Z
Learning: Applies to errors/errors.go : Define all static errors in errors/errors.go.

Applied to files:

  • pkg/merge/merge_context.go
📚 Learning: 2025-04-04T02:03:23.676Z
Learnt from: aknysh
PR: cloudposse/atmos#1185
File: internal/exec/yaml_func_store.go:26-26
Timestamp: 2025-04-04T02:03:23.676Z
Learning: The Atmos codebase currently uses `log.Fatal` for error handling in multiple places. The maintainers are aware this isn't an ideal pattern (should only be used in main() or init() functions) and plan to address it comprehensively in a separate PR. CodeRabbit should not flag these issues or push for immediate changes until that refactoring is complete.

Applied to files:

  • pkg/merge/merge_context.go
📚 Learning: 2025-09-13T18:06:07.674Z
Learnt from: samtholiya
PR: cloudposse/atmos#1466
File: toolchain/list.go:39-42
Timestamp: 2025-09-13T18:06:07.674Z
Learning: In the cloudposse/atmos repository, for UI messages in the toolchain package, use utils.PrintfMessageToTUI instead of log.Error or fmt.Fprintln(os.Stderr, ...). Import pkg/utils with alias "u" to follow the established pattern.

Applied to files:

  • pkg/merge/merge_context.go
📚 Learning: 2025-07-01T02:22:25.901Z
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*.go : Consider using a custom error type for domain-specific errors

Applied to files:

  • pkg/merge/merge_context.go
📚 Learning: 2025-09-10T22:38:42.212Z
Learnt from: Benbentwo
PR: cloudposse/atmos#1475
File: pkg/auth/identities/aws/user.go:141-145
Timestamp: 2025-09-10T22:38:42.212Z
Learning: ErrWrappingFormat is correctly defined as "%w: %w" in the errors package and is used throughout the codebase to wrap two error types together. The usage fmt.Errorf(errUtils.ErrWrappingFormat, errUtils.ErrAuthAwsFileManagerFailed, err) is the correct pattern when both arguments are error types.

Applied to files:

  • pkg/merge/merge_context.go
🧬 Code graph analysis (1)
pkg/merge/merge_context.go (1)
cmd/cmd_utils.go (1)
  • Contains (762-769)
⏰ 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). (3)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Lint (golangci)
  • GitHub Check: Summary
🔇 Additional comments (2)
pkg/merge/merge_context.go (2)

122-125: Nice: sentinel preserved.

Returning fmt.Errorf("%w...") keeps ErrMerge discoverable via errors.Is. Thanks for fixing the earlier issue.


57-125: Add missing sentinel-preservation test and fix comment-check.

  • Missing test: add a unit test asserting errors.Is(mc.FormatError(baseErr), errUtils.ErrMerge) (suggest: pkg/merge/merge_context_test.go — TestFormatError_PreservesErrMerge).
  • Comment-scan failed (PCRE2 compile error): manually verify comments in pkg/merge/merge_context.go (lines 57–125) end with periods, excluding inline nolint lines, or fix the grep/PCRE pattern.
  • Sanity: FormatError wraps with %w (return at line 124), so behavior is correct — test is required to prevent regressions.

Comment thread pkg/merge/merge_context.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (5)
demo_enhanced_errors.md (5)

9-14: Add language to fenced code block (markdownlint MD040).

Specify a language for the code fence to satisfy linters and improve rendering.

Apply this diff:

-```
+```text
 cannot override two slices with different type ([]interface {}, string)
 cannot override two slices with different type ([]interface {}, string)
 cannot override two slices with different type ([]interface {}, string)
 ...

---

`25-28`: **Add language to fenced code block (markdownlint MD040).**

This block is plain output; use text.


```diff
-```
+```text
 cannot override two slices with different type ([]interface {}, string)

---

`30-48`: **Add language to fenced code block (markdownlint MD040).**

This is also plain output; use text.


```diff
-```
+```text
 cannot override two slices with different type ([]interface {}, string)

   File being processed: stacks/deploy/prod/us-east-1.yaml
   Import chain:
     → stacks/orgs/acme/_defaults.yaml
       → stacks/catalog/vpc/defaults.yaml
       → stacks/catalog/vpc/base.yaml
       → stacks/mixins/region/us-east-1.yaml
       → stacks/mixins/account/prod.yaml
       → stacks/deploy/prod/us-east-1.yaml

   Likely cause: A key is defined as an array in one file and as a string in another.
   Debug hint: Check the files above for keys that have different types.
   Common issues:
     - vars defined as both array and string
     - settings with inconsistent types across imports
     - overrides attempting to change field types

---

`63-72`: **Cross-reference the new APIs with file paths for discoverability.**

Add file paths (e.g., pkg/merge/merge.go, internal/exec/stack_processor_utils.go) next to symbols so readers can jump to sources.

---

`88-99`: **Add a runnable example invocation.**

A small command example helps users reproduce the enhanced error output.


```diff
 With the enhanced error messages, the user can:
 1. See exactly which file is being processed when the error occurs
 2. Trace back through the import chain to find conflicting definitions
 3. Use the provided hints to identify the type mismatch
 4. Fix the configuration quickly without extensive debugging
+
+### Try it
+```bash
+# Replace the stack selector with one that triggers a type mismatch in your repo
+atmos validate stacks --stack deploy/prod/us-east-1 --debug
+```
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between d07a548 and 82aa34d.

📒 Files selected for processing (1)
  • demo_enhanced_errors.md (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-06-02T14:12:02.710Z
Learnt from: milldr
PR: cloudposse/atmos#1229
File: internal/exec/workflow_test.go:0-0
Timestamp: 2025-06-02T14:12:02.710Z
Learning: In the atmos codebase, workflow error handling was refactored to use `PrintErrorMarkdown` followed by returning specific error variables (like `ErrWorkflowNoSteps`, `ErrInvalidFromStep`, `ErrInvalidWorkflowStepType`, `ErrWorkflowStepFailed`) instead of `PrintErrorMarkdownAndExit`. This pattern allows proper error testing without the function terminating the process with `os.Exit`, enabling unit tests to assert on error conditions while maintaining excellent user-facing error formatting.

Applied to files:

  • demo_enhanced_errors.md
📚 Learning: 2025-06-02T14:12:02.710Z
Learnt from: milldr
PR: cloudposse/atmos#1229
File: internal/exec/workflow_test.go:0-0
Timestamp: 2025-06-02T14:12:02.710Z
Learning: In the atmos codebase, workflow error handling was refactored to use `PrintErrorMarkdown` followed by returning the error instead of `PrintErrorMarkdownAndExit`. This pattern allows proper error testing without the function terminating the process with `os.Exit`, enabling unit tests to assert on error conditions.

Applied to files:

  • demo_enhanced_errors.md
🪛 markdownlint-cli2 (0.18.1)
demo_enhanced_errors.md

9-9: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


25-25: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


30-30: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

⏰ 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). (6)
  • GitHub Check: Build (ubuntu-latest, linux)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Analyze (go)
  • GitHub Check: Lint (golangci)
  • GitHub Check: Run pre-commit hooks
  • GitHub Check: Summary
🔇 Additional comments (1)
demo_enhanced_errors.md (1)

52-56: Nice: no direct stderr prints; errors flow through logging.

This aligns with the codebase pattern to return errors and let callers format/log, preventing duplicates.

@aknysh
Andriy Knysh (aknysh) merged commit 6274d75 into main Sep 23, 2025
@aknysh
Andriy Knysh (aknysh) deleted the improve-atmos-validate branch September 23, 2025 13:43
@github-actions

Copy link
Copy Markdown

These changes were released in v1.191.0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

minor New features that do not break anything size/xl Extra large size PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants