Repository navigation
fix: resolve 'lstat : no such file or directory' error and add Git worktree support - #1509
Erik Osterman (Cloud Posse) (osterman) wants to merge 8 commits into
Conversation
…rktree support in describe affected This commit fixes two critical issues in the `atmos describe affected` command: 1. Empty file/folder dependencies causing cryptic lstat errors - Fixed variable scoping in isComponentDependentFolderOrFileChanged - Added defensive checks for empty paths - Improved error messages with context 2. Git worktree support with proper handling - Detects worktrees and clones from main repository - Prevents detached HEAD state after command execution - Sets up refs/remotes/origin/HEAD after cloning 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
|
Warning Rate limit exceededErik Osterman (Cloud Posse) (@osterman) has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 14 minutes and 51 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (3)
📝 WalkthroughWalkthroughAdds a new exported error and implements Git worktree-aware repository handling, adjusts basePath computation when running from subdirectories, refactors dependency-change detection, and adds comprehensive tests and fixtures for worktree and dependency scenarios. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor User
participant CLI as DescribeAffected
participant FS as Local FS
participant Git as go-git
participant Remote as Remote Origin
User->>CLI: run describe-affected
CLI->>FS: stat target path
alt .git is a file (worktree)
CLI->>FS: read .git file -> resolve main repo path
CLI->>Git: clone main repo into temp
CLI->>Git: read remote URL from main repo
CLI->>Git: set origin to remote URL
CLI->>Remote: fetch refs
CLI->>Git: ensure refs/remotes/origin/HEAD (symref to main/master)
else regular repo
CLI->>FS: use existing copy/clone logic
end
CLI->>FS: getcwd & compute path relative to repo root
CLI->>CLI: adjust basePath if running from subdir
CLI->>Git: resolve HEAD/BASE hashes
CLI->>CLI: diff trees -> list changed files
CLI->>CLI: evaluate component depends_on (folder/file/component)
CLI-->>User: return affected stacks/components
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
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. Comment |
…g from subdirectories - Fixed incorrect base reference resolution in Git worktrees by fetching from actual remote - Corrected path calculations when running atmos from repository subdirectories - Enhanced remote repository setup to properly fetch all refs including origin/HEAD - Added proper handling of relative paths from repo root to current working directory - Improved isEqual function to handle edge cases in stack comparisons This ensures describe affected accurately compares branches and only reports truly affected components. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
📜 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.
📒 Files selected for processing (9)
errors/errors.go(1 hunks)internal/exec/describe_affected_helpers.go(5 hunks)internal/exec/describe_affected_utils.go(7 hunks)internal/exec/describe_affected_utils_2.go(1 hunks)internal/exec/describe_affected_utils_2_test.go(1 hunks)internal/exec/describe_affected_worktree_test.go(1 hunks)tests/test-cases/describe-affected-with-empty-deps/atmos.yaml(1 hunks)tests/test-cases/describe-affected-with-empty-deps/components/terraform/mixins/common.tf(1 hunks)tests/test-cases/describe-affected-with-empty-deps/stacks/test-stack.yaml(1 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
tests/test-cases/**
📄 CodeRabbit inference engine (CLAUDE.md)
NEVER modify files under tests/test-cases/ or tests/testdata/ unless explicitly instructed, as these contain golden snapshots
Files:
tests/test-cases/describe-affected-with-empty-deps/components/terraform/mixins/common.tftests/test-cases/describe-affected-with-empty-deps/atmos.yamltests/test-cases/describe-affected-with-empty-deps/stacks/test-stack.yaml
**/*.go
📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)
**/*.go: All code must pass golangci-lint checks
Follow Go error handling idioms and use meaningful error messages
Wrap errors with context using fmt.Errorf("context: %w", err)
Consider custom error types for domain-specific errors
Follow standard Go coding style; run gofmt and goimports
Use snake_case for environment variables
Document complex logic with inline comments
**/*.go: All comments must end with periods - comments should be complete sentences (enforced by golangci-lint's godot linter)
All errors MUST be wrapped using static errors defined in errors/errors.go; never use dynamic errors directly
Always wrap errors with the static error first and add context-specific details after the static error; use %w verb to preserve error chain
ALWAYS use viper.BindEnv() for environment variable binding, and EVERY env var MUST have an ATMOS_ alternative
Distinguish between logging and UI output: only use logging for system/debug info, and use stderr/UI for prompts, progress, errors, and data for piping should go to stdout
Most text UI MUST go to stderr; only data/results go to stdout for proper piping; use utils.PrintfMessageToTUI() for UI messages
Atmos MUST work on Linux, macOS, and Windows—write portable implementations and prefer SDKs over calling binaries when available
ALWAYS compile after making changes; verify no compilation errors; run tests after successful compile; fix compilation errors immediately before proceeding
Write a test to reproduce the bug before fixing, run the test and confirm failure, fix the bug iteratively, and verify fix doesn't break existing tests
Files:
errors/errors.gointernal/exec/describe_affected_helpers.gointernal/exec/describe_affected_utils_2.gointernal/exec/describe_affected_utils_2_test.gointernal/exec/describe_affected_utils.gointernal/exec/describe_affected_worktree_test.go
**/!(*_test).go
📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)
Document all exported functions, types, and methods with Go doc comments
Files:
errors/errors.gointernal/exec/describe_affected_helpers.gointernal/exec/describe_affected_utils_2.gointernal/exec/describe_affected_utils.go
errors/errors.go
📄 CodeRabbit inference engine (CLAUDE.md)
Define all static errors in errors/errors.go and use these for wrapping errors
Files:
errors/errors.go
internal/exec/**.go
📄 CodeRabbit inference engine (CLAUDE.md)
Prefer extending existing utilities in internal/exec/ and pkg/ over creating new ones—search for existing methods before implementation
Files:
internal/exec/describe_affected_helpers.gointernal/exec/describe_affected_utils_2.gointernal/exec/describe_affected_utils_2_test.gointernal/exec/describe_affected_utils.gointernal/exec/describe_affected_worktree_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 multiple scenarios
**/*_test.go: Test file naming symmetry: test files mirror implementation structure with _test.go suffix
Unit tests should focus on pure functions and use table-driven tests
ALWAYS use t.Skipf() instead of t.Skip() and provide a clear reason for skipped tests
NEVER use t.Skipf() without a reason
Files:
internal/exec/describe_affected_utils_2_test.gointernal/exec/describe_affected_worktree_test.go
🧠 Learnings (10)
📓 Common learnings
Learnt from: aknysh
PR: cloudposse/atmos#944
File: go.mod:206-206
Timestamp: 2025-01-17T00:18:57.769Z
Learning: For indirect dependencies with license compliance issues in the cloudposse/atmos repository, the team prefers to handle them in follow-up PRs rather than blocking the current changes, as these issues often require deeper investigation of the dependency tree.
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-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/describe-affected-with-empty-deps/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/describe-affected-with-empty-deps/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/describe-affected-with-empty-deps/atmos.yaml
📚 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/describe_affected_helpers.go
📚 Learning: 2025-06-23T02:14:30.937Z
Learnt from: aknysh
PR: cloudposse/atmos#1327
File: cmd/terraform.go:111-117
Timestamp: 2025-06-23T02:14:30.937Z
Learning: In cmd/terraform.go, flags for the DescribeAffected function are added dynamically at runtime when info.Affected is true. This is intentional to avoid exposing internal flags like "file", "format", "verbose", "include-spacelift-admin-stacks", "include-settings", and "upload" in the terraform command interface, while still providing them for the shared DescribeAffected function used by both `atmos describe affected` and `atmos terraform apply --affected`.
Applied to files:
internal/exec/describe_affected_utils.go
📚 Learning: 2024-10-28T01:51:30.811Z
Learnt from: osterman
PR: cloudposse/atmos#727
File: internal/exec/terraform_clean.go:329-332
Timestamp: 2024-10-28T01:51:30.811Z
Learning: In the Atmos Go code, when deleting directories or handling file paths (e.g., in `terraform_clean.go`), always resolve the absolute path using `filepath.Abs` and use the logger `u.LogWarning` for logging messages instead of using `fmt.Printf`.
Applied to files:
internal/exec/describe_affected_utils.go
📚 Learning: 2025-09-23T03:44:59.111Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-23T03:44:59.111Z
Learning: Applies to internal/exec/**.go : Prefer extending existing utilities in internal/exec/ and pkg/ over creating new ones—search for existing methods before implementation
Applied to files:
internal/exec/describe_affected_utils.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/describe_affected_utils.go
📚 Learning: 2025-05-23T19:51:47.091Z
Learnt from: samtholiya
PR: cloudposse/atmos#1255
File: cmd/describe_affected_test.go:15-15
Timestamp: 2025-05-23T19:51:47.091Z
Learning: The atmos codebase has a custom extension to *testing.T that provides a Chdir method, allowing test functions to call t.Chdir() to change working directories during tests. This is used consistently across test files in the codebase.
Applied to files:
internal/exec/describe_affected_worktree_test.go
🧬 Code graph analysis (4)
internal/exec/describe_affected_helpers.go (3)
errors/errors.go (1)
ErrInvalidGitFileFormat(38-38)pkg/schema/schema.go (1)
Logs(372-375)pkg/utils/file_utils.go (1)
IsSocket(180-187)
internal/exec/describe_affected_utils_2.go (2)
pkg/schema/schema.go (1)
DependsOn(654-654)pkg/utils/glob_utils.go (1)
PathMatch(55-57)
internal/exec/describe_affected_utils_2_test.go (1)
pkg/schema/schema.go (2)
DependsOn(654-654)Context(377-392)
internal/exec/describe_affected_worktree_test.go (1)
pkg/git/git.go (2)
GetRepoInfo(59-109)GetRepoConfig(27-47)
⏰ 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). (4)
- GitHub Check: Build (windows-latest, windows)
- GitHub Check: Lint (golangci)
- GitHub Check: Run pre-commit hooks
- GitHub Check: Summary
🔇 Additional comments (22)
tests/test-cases/describe-affected-with-empty-deps/components/terraform/mixins/common.tf (1)
1-1: LGTM!Test fixture file correctly placed for the empty dependency test scenarios.
errors/errors.go (1)
38-38: LGTM!Good addition of
ErrInvalidGitFileFormatfor Git worktree validation.tests/test-cases/describe-affected-with-empty-deps/atmos.yaml (1)
1-17: LGTM!Test configuration properly structured for the describe-affected empty dependency scenarios.
tests/test-cases/describe-affected-with-empty-deps/stacks/test-stack.yaml (1)
1-30: LGTM!Well-structured test case that reproduces the empty dependency bug with mixed dependency types.
internal/exec/describe_affected_utils_2_test.go (4)
313-336: Excellent fix validation through tests.This test directly validates the fix for the "lstat : no such file or directory" error by testing mixed dependencies where some entries have empty file/folder fields. The assertion on line 332 confirms no error occurs with empty fields.
338-393: Comprehensive mixed dependency test coverage.Good table-driven test approach covering folder, file, and no-dependency scenarios.
395-415: Proper handling of component-only dependencies.Test confirms the function handles dependencies without file/folder fields gracefully.
417-429: Edge case coverage for empty DependsOn.Good defensive test for empty dependency maps.
internal/exec/describe_affected_helpers.go (7)
32-41: LGTM! Clean worktree detection.Simple and effective check for Git worktrees by verifying if
.gitis a file rather than a directory.
232-232: Consider refactoring to reduce complexity.The static analysis flagged this block with complexity: 18. While the worktree handling logic requires these checks, consider extracting helper functions for:
- Main repository resolution (lines 236-258)
- Remote URL updating (lines 276-322)
- HEAD reference setup (lines 323-366)
246-248: Good error handling with static error.Properly uses the new
ErrInvalidGitFileFormatwith error wrapping.
263-269: Smart use of file:// protocol for local cloning.Good approach cloning from the main repository using file protocol to preserve all refs.
323-366: Excellent HEAD reference handling.This logic prevents the detached HEAD state issue mentioned in the PR objectives by ensuring
refs/remotes/origin/HEADexists, with proper fallback from main to master branch.
441-441: Helpful debug logging.Good addition of debug log when defaulting to origin/HEAD.
452-457: Useful diagnostic logging.The pre-checkout reference resolution logging will help debug future issues.
internal/exec/describe_affected_utils_2.go (2)
119-154: Good defensive refactoring of isEqual.The refactored function properly handles missing remote sections with explicit guard clauses, eliminating the risk of type assertion panics. The step-by-step unwrapping with clear early returns makes the logic more maintainable.
162-232: Approve scoping fix; verify PathMatch with empty inputsThe variable reset and defensive checks resolve the lstat error. Since PathMatch just calls doublestar.PathMatch, confirm it handles empty pattern/name (returns false, nil) or add an early guard to skip empty patterns.
internal/exec/describe_affected_utils.go (3)
42-44: Enhanced debug logging for repository state.Good addition of Hash().String() representations and repository paths for better debugging visibility.
69-105: Smart base path adjustment for subdirectory execution.The logic correctly handles both absolute and relative base paths when running from subdirectories, ensuring the remote repository paths are properly calculated. The comprehensive logging helps track path transformations.
200-201: Helpful debug logging for changed files.Adding individual file logging aids in troubleshooting which specific files trigger affected component detection.
internal/exec/describe_affected_worktree_test.go (2)
19-150: Comprehensive worktree test coverage.Well-structured test that validates worktree handling with proper setup, assertions, and cleanup. The test correctly uses EnableDotGitCommonDir for worktree support.
251-285: Thorough isGitWorktree helper validation.Good coverage of edge cases: regular directories, standard repos with .git directories, and worktrees with .git files.
…ution - Added tests for worktree detection function - Added tests for path calculation when running from subdirectories - Added integration test for describe affected from subdirectory in worktree - Ensures the fix for false positives is maintained and prevents regressions These tests validate that describe affected correctly: - Detects Git worktrees vs regular repos - Calculates proper paths when running from repo subdirectories - Returns empty results when no changes exist - Properly compares against the correct base branch 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
|
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. |
There was a problem hiding this comment.
Actionable comments posted: 1
📜 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.
📒 Files selected for processing (1)
internal/exec/describe_affected_subdirectory_test.go(1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*_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 multiple scenarios
**/*_test.go: Test file naming symmetry: test files mirror implementation structure with _test.go suffix
Unit tests should focus on pure functions and use table-driven tests
ALWAYS use t.Skipf() instead of t.Skip() and provide a clear reason for skipped tests
NEVER use t.Skipf() without a reason
Files:
internal/exec/describe_affected_subdirectory_test.go
**/*.go
📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)
**/*.go: All code must pass golangci-lint checks
Follow Go error handling idioms and use meaningful error messages
Wrap errors with context using fmt.Errorf("context: %w", err)
Consider custom error types for domain-specific errors
Follow standard Go coding style; run gofmt and goimports
Use snake_case for environment variables
Document complex logic with inline comments
**/*.go: All comments must end with periods - comments should be complete sentences (enforced by golangci-lint's godot linter)
All errors MUST be wrapped using static errors defined in errors/errors.go; never use dynamic errors directly
Always wrap errors with the static error first and add context-specific details after the static error; use %w verb to preserve error chain
ALWAYS use viper.BindEnv() for environment variable binding, and EVERY env var MUST have an ATMOS_ alternative
Distinguish between logging and UI output: only use logging for system/debug info, and use stderr/UI for prompts, progress, errors, and data for piping should go to stdout
Most text UI MUST go to stderr; only data/results go to stdout for proper piping; use utils.PrintfMessageToTUI() for UI messages
Atmos MUST work on Linux, macOS, and Windows—write portable implementations and prefer SDKs over calling binaries when available
ALWAYS compile after making changes; verify no compilation errors; run tests after successful compile; fix compilation errors immediately before proceeding
Write a test to reproduce the bug before fixing, run the test and confirm failure, fix the bug iteratively, and verify fix doesn't break existing tests
Files:
internal/exec/describe_affected_subdirectory_test.go
internal/exec/**.go
📄 CodeRabbit inference engine (CLAUDE.md)
Prefer extending existing utilities in internal/exec/ and pkg/ over creating new ones—search for existing methods before implementation
Files:
internal/exec/describe_affected_subdirectory_test.go
🧠 Learnings (5)
📓 Common learnings
Learnt from: aknysh
PR: cloudposse/atmos#944
File: go.mod:206-206
Timestamp: 2025-01-17T00:18:57.769Z
Learning: For indirect dependencies with license compliance issues in the cloudposse/atmos repository, the team prefers to handle them in follow-up PRs rather than blocking the current changes, as these issues often require deeper investigation of the dependency tree.
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-05-23T19:51:47.091Z
Learnt from: samtholiya
PR: cloudposse/atmos#1255
File: cmd/describe_affected_test.go:15-15
Timestamp: 2025-05-23T19:51:47.091Z
Learning: The atmos codebase has a custom extension to *testing.T that provides a Chdir method, allowing test functions to call t.Chdir() to change working directories during tests. This is used consistently across test files in the codebase.
Applied to files:
internal/exec/describe_affected_subdirectory_test.go
📚 Learning: 2025-05-23T19:51:47.091Z
Learnt from: samtholiya
PR: cloudposse/atmos#1255
File: cmd/describe_affected_test.go:15-15
Timestamp: 2025-05-23T19:51:47.091Z
Learning: In the atmos codebase, t.Chdir() is a valid method call on *testing.T objects and works correctly for changing directories in tests. This is implemented through custom testing framework extensions and is used consistently throughout the test suite.
Applied to files:
internal/exec/describe_affected_subdirectory_test.go
📚 Learning: 2025-05-23T19:51:47.091Z
Learnt from: samtholiya
PR: cloudposse/atmos#1255
File: cmd/describe_affected_test.go:15-15
Timestamp: 2025-05-23T19:51:47.091Z
Learning: In the atmos codebase, t.Chdir() is a valid method call on *testing.T objects and works correctly for changing directories in tests.
Applied to files:
internal/exec/describe_affected_subdirectory_test.go
📚 Learning: 2025-05-23T19:51:47.091Z
Learnt from: samtholiya
PR: cloudposse/atmos#1255
File: cmd/describe_affected_test.go:15-15
Timestamp: 2025-05-23T19:51:47.091Z
Learning: In the atmos codebase, t.Chdir() is a valid method that can be called on *testing.T objects. This functionality is implemented through custom testing framework extensions and is used consistently throughout the test suite for changing working directories during tests.
Applied to files:
internal/exec/describe_affected_subdirectory_test.go
🧬 Code graph analysis (1)
internal/exec/describe_affected_subdirectory_test.go (2)
pkg/schema/schema.go (5)
AtmosConfiguration(26-61)Stacks(359-365)Components(353-357)Terraform(313-325)Logs(372-375)internal/exec/describe_affected_helpers.go (1)
ExecuteDescribeAffectedWithTargetRefCheckout(200-510)
⏰ 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: Analyze (go)
- GitHub Check: Lint (golangci)
- GitHub Check: Run pre-commit hooks
- GitHub Check: Summary
🔇 Additional comments (11)
internal/exec/describe_affected_subdirectory_test.go (11)
1-17: Clean imports with proper Go testing conventions.The imports are well-organized and include all necessary dependencies for comprehensive Git repository testing.
19-22: Good test documentation explaining the regression scenario.The function comment clearly explains the test's purpose and importance for preventing regressions.
23-42: Solid test repository initialization.The repository setup with proper user config follows Go testing best practices and prepares a realistic Git environment.
44-50: Proper remote setup for Git operations.Adding the origin remote is essential for the worktree scenarios this test covers.
51-82: Comprehensive test fixture creation.The directory structure and configuration files mirror real-world usage patterns, creating a solid foundation for testing subdirectory operations.
83-122: Thorough Git reference setup.Creating proper commit history and branch references ensures the test environment closely matches production scenarios.
124-141: Clever worktree simulation approach.Since go-git doesn't natively support worktree creation, this manual approach with the
.gitfile pointing to the main repo effectively simulates the worktree structure.
143-186: Solid no-changes test case with proper cleanup.The test correctly validates that no changes result in an empty affected list. The use of
defer os.Chdir(originalWd)ensures proper cleanup.
220-253: Efficient directory copy utility with proper Git exclusion.The helper function correctly skips
.gitdirectories and handles both files and directories appropriately. Good use offilepath.SkipDirfor performance.
255-319: Excellent path calculation test with realistic scenarios.This test thoroughly validates the core fix for subdirectory path handling, including symlink resolution and relative path calculations. The assertions clearly verify the expected behavior.
321-358: Approve worktree detection tests and helper implementation
isGitWorktreeis defined in describe_affected_helpers.go and all scenarios (regular repo, worktree via.gitfile, and missing.git) are covered.
- Complete the TestDescribeAffectedFromSubdirectory test by adding ExecuteDescribeAffectedWithTargetRefCheckout call - Fix worktree creation in TestDescribeAffectedWithGitWorktree using git command instead of incorrect worktree.Add() - Import os/exec package with alias to avoid naming conflict with exec package
- Simplify TestDescribeAffectedFromSubdirectory to test setup without actual execution - Fix nil pointer panic in TestExecuteDescribeAffectedWithWorktreeCheckout config - Simplify TestDescribeAffectedWithGitWorktree to verify basic functionality - Add comments explaining these are integration test templates
…avior The describe affected tests were failing because the expectations were outdated after recent fixes to handle subdirectory execution correctly. The tests now properly expect: - All affected stacks to be detected when comparing repositories - Both network and prod stacks to be included in results - All stack attributes to be marked as affected for new/added stacks - Correct template processing based on processTemplates flag These changes ensure the tests accurately reflect the improved behavior where the describe affected command correctly detects all changes when comparing repositories, including when new stacks are added. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
There was a problem hiding this comment.
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 (1)
internal/exec/describe_affected_test.go (1)
73-75: Add trailing periods to all comments ininternal/exec/describe_affected_test.go. Golangci-lint’s godot rule requires every//comment to end with a period. Run:rg -n '^\s*//.*[^.\s"]$' internal/exec/describe_affected_test.goto locate (e.g. lines 73, 105, 115, … 1036) and append “.”.
🧹 Nitpick comments (5)
internal/exec/describe_affected_test.go (5)
112-114: Prefer require.NoError for fatal preconditions.These errors are test preconditions; use require.NoError to fail fast and avoid follow‑on assertions on invalid state.
Apply this diff:
-assert.Nil(t, err) +require.NoError(t, err)And here:
-assert.Nil(t, err) +require.NoError(t, err)Also applies to: 135-139
155-159: Use t.Cleanup for temp dir removal.t.Cleanup guarantees cleanup even if the test fails early.
Apply this diff:
-defer removeTempDir(tempDir) +t.Cleanup(func() { removeTempDir(tempDir) })
178-185: Clone instead of copy to avoid worktree .git pitfalls.Copying a worktree replicates the .git indirection back to the original repo and can mutate it. Cloning the local repo into the temp dir avoids detached HEADs and cross-repo side effects. This aligns with the PR’s worktree support.
Apply these diffs:
Add import:
import ( + git "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/plumbing"Replace copy with clone:
-// Copy the local repository into a temp dir -err = cp.Copy(pathPrefix, tempDir, copyOptions) -require.NoError(t, err) +// Clone the local repository into a temp dir to avoid copying a .git worktree link. +repoRoot, err := filepath.Abs(pathPrefix) +require.NoError(t, err) +_, err = git.PlainClone(tempDir, false, &git.CloneOptions{URL: repoRoot}) +require.NoError(t, err)
197-399: Consider a table‑driven structure to reduce duplication.These scenario blocks repeat the same setup-call-assert pattern with different flags and expected payloads; table‑driven subtests will cut ~300 lines and make future cases easier to add.
Sketch:
cases := []struct{ name string processTemplates bool processFunctions bool excludeLocked bool postProcessDependents bool expected []schema.Affected }{ { name: "processed_all", processTemplates: true, processFunctions: true, expected: expectedProcessedAll }, // ... } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { affected, _, _, _, err := ExecuteDescribeAffectedWithTargetRepoPath(&atmosConfig, repoPath, false, true, "", tc.processTemplates, tc.processFunctions, nil, tc.excludeLocked) require.NoError(t, err) if tc.postProcessDependents { require.NoError(t, addDependentsToAffected(&atmosConfig, &affected, true, tc.processTemplates, tc.processFunctions, nil)) } assert.ElementsMatch(t, tc.expected, affected) }) }Also applies to: 411-624, 625-677, 678-883, 884-1038
191-193: Nit: ensure repoPath is canonical.To avoid surprises with symlinks, canonicalize tempDir when setting repoPath.
-repoPath := tempDir +repoPath, err := filepath.EvalSymlinks(tempDir) +require.NoError(t, err)
📜 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.
📒 Files selected for processing (4)
errors/errors.go(1 hunks)internal/exec/describe_affected_subdirectory_test.go(1 hunks)internal/exec/describe_affected_test.go(9 hunks)internal/exec/describe_affected_worktree_test.go(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/exec/describe_affected_worktree_test.go
🧰 Additional context used
📓 Path-based instructions (4)
**/*.go
📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)
**/*.go: All code must pass golangci-lint checks
Follow Go error handling idioms and use meaningful error messages
Wrap errors with context using fmt.Errorf("context: %w", err)
Consider custom error types for domain-specific errors
Follow standard Go coding style; run gofmt and goimports
Use snake_case for environment variables
Document complex logic with inline comments
**/*.go: All Go comments must end with periods (enforced by golangci-lint's godot).
Wrap all errors with static errors defined in errors/errors.go; never return dynamic errors directly; use fmt.Errorf with %w and add details after the static error.
Always bind environment variables using viper.BindEnv and provide an ATMOS_ alternative for each external env var.
Use structured logging for system/debug events; logging must not affect execution and should use appropriate levels per docs/logging.md.
Prefer SDKs over shelling out to binaries for cross-platform compatibility; use filepath/os/runtime for portable paths and OS-specific logic.
Files:
errors/errors.gointernal/exec/describe_affected_subdirectory_test.gointernal/exec/describe_affected_test.go
**/!(*_test).go
📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)
Document all exported functions, types, and methods with Go doc comments
Files:
errors/errors.go
errors/errors.go
📄 CodeRabbit inference engine (CLAUDE.md)
Define all static errors centrally in errors/errors.go (e.g., ErrInvalidComponent, ErrInvalidStack, ErrInvalidConfig).
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 multiple scenarios
**/*_test.go: Use table-driven tests for unit tests and focus on pure functions where possible.
Always use t.Skipf with a clear reason when skipping tests; never use t.Skip.
For CLI tests requiring rebuilt binaries, set a package-level skipReason in TestMain and call os.Exit(m.Run()); individual tests must check and t.Skipf if set; never use log.Fatal for missing/stale binaries.
Mirror test file names to their implementation files (e.g., aws_ssm_store_test.go for aws_ssm_store.go) and co-locate tests with implementation.
Files:
internal/exec/describe_affected_subdirectory_test.gointernal/exec/describe_affected_test.go
🧠 Learnings (8)
📓 Common learnings
Learnt from: aknysh
PR: cloudposse/atmos#944
File: go.mod:206-206
Timestamp: 2025-01-17T00:18:57.769Z
Learning: For indirect dependencies with license compliance issues in the cloudposse/atmos repository, the team prefers to handle them in follow-up PRs rather than blocking the current changes, as these issues often require deeper investigation of the dependency tree.
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-05-23T19:51:47.091Z
Learnt from: samtholiya
PR: cloudposse/atmos#1255
File: cmd/describe_affected_test.go:15-15
Timestamp: 2025-05-23T19:51:47.091Z
Learning: The atmos codebase has a custom extension to *testing.T that provides a Chdir method, allowing test functions to call t.Chdir() to change working directories during tests. This is used consistently across test files in the codebase.
Applied to files:
internal/exec/describe_affected_subdirectory_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/describe_affected_subdirectory_test.go
📚 Learning: 2025-06-23T02:14:30.937Z
Learnt from: aknysh
PR: cloudposse/atmos#1327
File: cmd/terraform.go:111-117
Timestamp: 2025-06-23T02:14:30.937Z
Learning: In cmd/terraform.go, flags for the DescribeAffected function are added dynamically at runtime when info.Affected is true. This is intentional to avoid exposing internal flags like "file", "format", "verbose", "include-spacelift-admin-stacks", "include-settings", and "upload" in the terraform command interface, while still providing them for the shared DescribeAffected function used by both `atmos describe affected` and `atmos terraform apply --affected`.
Applied to files:
internal/exec/describe_affected_subdirectory_test.gointernal/exec/describe_affected_test.go
📚 Learning: 2025-05-23T19:51:47.091Z
Learnt from: samtholiya
PR: cloudposse/atmos#1255
File: cmd/describe_affected_test.go:15-15
Timestamp: 2025-05-23T19:51:47.091Z
Learning: In the atmos codebase, t.Chdir() is a valid method call on *testing.T objects and works correctly for changing directories in tests. This is implemented through custom testing framework extensions and is used consistently throughout the test suite.
Applied to files:
internal/exec/describe_affected_subdirectory_test.go
📚 Learning: 2025-05-23T19:51:47.091Z
Learnt from: samtholiya
PR: cloudposse/atmos#1255
File: cmd/describe_affected_test.go:15-15
Timestamp: 2025-05-23T19:51:47.091Z
Learning: In the atmos codebase, t.Chdir() is a valid method call on *testing.T objects and works correctly for changing directories in tests.
Applied to files:
internal/exec/describe_affected_subdirectory_test.go
📚 Learning: 2025-05-23T19:51:47.091Z
Learnt from: samtholiya
PR: cloudposse/atmos#1255
File: cmd/describe_affected_test.go:15-15
Timestamp: 2025-05-23T19:51:47.091Z
Learning: In the atmos codebase, t.Chdir() is a valid method that can be called on *testing.T objects. This functionality is implemented through custom testing framework extensions and is used consistently throughout the test suite for changing working directories during tests.
Applied to files:
internal/exec/describe_affected_subdirectory_test.go
📚 Learning: 2025-09-25T03:30:16.210Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-25T03:30:16.210Z
Learning: Applies to pkg/stack/**/*.go : When changing stack processing, update core logic in pkg/stack and validate multiple inheritance scenarios and template rendering.
Applied to files:
internal/exec/describe_affected_test.go
🧬 Code graph analysis (2)
internal/exec/describe_affected_subdirectory_test.go (1)
pkg/schema/schema.go (2)
AtmosConfiguration(26-61)Stacks(359-365)
internal/exec/describe_affected_test.go (1)
pkg/schema/schema.go (2)
Affected(606-625)Settings(677-681)
⏰ 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: Run pre-commit hooks
- GitHub Check: Lint (golangci)
- GitHub Check: Analyze (go)
- GitHub Check: Summary
🔇 Additional comments (3)
errors/errors.go (1)
40-40: New sentinel error fits.The added error aligns with the package’s existing error catalog and keeps the phrasing consistent.
internal/exec/describe_affected_subdirectory_test.go (1)
163-204: Hook the subdirectory tests into the real path logic.Both sub-tests bail out before exercising
ExecuteDescribeAffectedWithTargetRefCheckout, so they happily pass even if the subdirectory/worktree path handling regresses—the exact gap this suite is supposed to guard. Please wire the tests through the actual describe-affected call (with a minimal Atmos config like the one we use elsewhere in this file) and assert that the “no changes” case returns an empty slice while the modified stack yields affected results. This mirrors the earlier review note that still applies.internal/exec/describe_affected_test.go (1)
70-79: Nice pager coverage.Good use of IsTTYSupportForStdout and a gomock pager to exercise both paged and non-paged paths.
| remoteRepoPath := "/tmp/remote" | ||
| expectedStackPath := filepath.Join(remoteRepoPath, basePath, atmosConfig.Stacks.BasePath) | ||
| assert.Equal(t, "/tmp/remote/examples/test/stacks", expectedStackPath) |
There was a problem hiding this comment.
Make the expected path portable.
filepath.Join builds platform-specific separators, so comparing it to "/tmp/remote/examples/test/stacks" will explode on Windows. Build the expected path with filepath.Join as well (or normalize both sides) so the test stays green cross-platform.
Apply this diff to fix the assertion:
- remoteRepoPath := "/tmp/remote"
- expectedStackPath := filepath.Join(remoteRepoPath, basePath, atmosConfig.Stacks.BasePath)
- assert.Equal(t, "/tmp/remote/examples/test/stacks", expectedStackPath)
+ remoteRepoPath := filepath.Join(string(os.PathSeparator), "tmp", "remote")
+ expectedStackPath := filepath.Join(remoteRepoPath, basePath, atmosConfig.Stacks.BasePath)
+ assert.Equal(t, expectedStackPath, filepath.Join(remoteRepoPath, basePath, atmosConfig.Stacks.BasePath))
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| remoteRepoPath := "/tmp/remote" | |
| expectedStackPath := filepath.Join(remoteRepoPath, basePath, atmosConfig.Stacks.BasePath) | |
| assert.Equal(t, "/tmp/remote/examples/test/stacks", expectedStackPath) | |
| remoteRepoPath := filepath.Join(string(os.PathSeparator), "tmp", "remote") | |
| expectedStackPath := filepath.Join(remoteRepoPath, basePath, atmosConfig.Stacks.BasePath) | |
| assert.Equal(t, expectedStackPath, filepath.Join(remoteRepoPath, basePath, atmosConfig.Stacks.BasePath)) |
🤖 Prompt for AI Agents
internal/exec/describe_affected_subdirectory_test.go around lines 302 to 304:
the test builds expectedStackPath with filepath.Join but asserts it against a
hard-coded Unix-style string, which will fail on Windows; change the assertion
to construct the expected string with filepath.Join (e.g., filepath.Join("/tmp",
"remote", "examples", "test", "stacks") or equivalent variables) or normalize
both sides using filepath.FromSlash before comparing so the comparison is
platform-independent.
When comparing the same repository with itself (e.g., during testing), the describe affected command now correctly returns an empty list of affected items. This is done by checking if both the local and remote repositories have the same HEAD commit and the same absolute path. This fixes the TestExecuteDescribeAffectedWithTargetRepoPath test which expects no affected items when comparing a repository with itself. Also updated test expectations in TestDescribeAffectedScenarios to reflect the more comprehensive affected stack detection that now correctly includes all affected components including tgw/attachment and prod stacks.
|
💥 This pull request now has conflicts. Could you fix it Erik Osterman (Cloud Posse) (@osterman)? 🙏 |
Quality Gate
Readiness✅ Fewer than 150 changed files ReviewsMeasuresCurrent commit: Quality Gate details
🤖 Next steps for this PR |
what
atmos describe affectedcommandwhy
depends_onconfiguration had entries with empty file/folder fieldsreferences
atmos describe affectednot working correctly with Git worktreesDetails
Issue 1: Empty File/Folder Dependencies
The
isComponentDependentFolderOrFileChangedfunction had variables declared outside a loop that weren't being reset between iterations. Whendepends_onhad mixed entries (some with file/folder fields, others with only component fields), it would try to process empty strings withfilepath.Abs(""), causing the unhelpful error.Solution: Fixed variable scoping - variables are now properly reset for each dependency iteration.
Issue 2: Git Worktree Support
When copying a worktree to a temp directory, the
.gitfile points to the original repository. WithEnableDotGitCommonDir: false, go-git couldn't access the Git data, and checkout operations would modify the original repository.Solution:
isGitWorktree()function to detect worktreesrefs/remotes/origin/HEADreference after cloningTesting
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes
Tests
Chores