Repository navigation
fix: toolchain path resolution, constraint solving, and uninstall improvements - #2172
Conversation
Template functions like atmos.Component() and YAML functions like !terraform.output were failing with "exec: tofu: executable file not found in $PATH" even when tofu was installed via `atmos toolchain install`. The executor in pkg/terraform/output never set up the toolchain PATH, unlike the direct terraform command execution path. Changes: - Export ExtractDependenciesFromConfig in pkg/dependencies/resolver.go so the executor can extract dependencies.tools from component sections - Add ResolveExecutablePath method to Installer to resolve bare executable names (e.g., "tofu") to their absolute toolchain install paths - Add toolchain dependency resolution in executor.execute() between config extraction and runner creation: ensure tools are installed, resolve the executable to an absolute path, and build the toolchain PATH for subprocesses - Add comprehensive tests demonstrating the fix resolves toolchain executables This ensures all code paths that need to execute terraform/tofu (template functions, YAML functions, describe-stacks) can find toolchain-installed binaries. Co-Authored-By: Claude Haiku 4.5 <[email protected]>
Dependency Review✅ No vulnerabilities or license issues found.Scanned FilesNone |
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds a ToolchainEnvironment for resolving/installing toolchain binaries, exposes ExtractDependenciesFromConfig, integrates toolchain-aware executable resolution and PATH/env propagation across executors and internal commands, and updates tests and messaging related to CI artifact discovery. Changes
Sequence Diagram(s)sequenceDiagram
participant Executor as Terraform Executor
participant Resolver as Dependency Resolver
participant Installer as Tool Installer
participant PathFinder as Binary Path Finder
participant Runner as Runner Factory
Executor->>+Resolver: ExtractDependenciesFromConfig(config)
Resolver-->>-Executor: deps map
alt deps exist
Executor->>+Installer: ForSections/ForComponent(deps)
Installer-->>-Executor: ToolchainEnvironment (tenv)
Executor->>+PathFinder: tenv.Resolve(executable)
PathFinder-->>-Executor: resolved toolchain path or empty
alt found in toolchain
Executor->>Executor: use absolute toolchain path
else not found
Executor->>Executor: exec.LookPath(executable)
Executor-->>Executor: system PATH result or original name
end
Executor->>Executor: updatedPATH = tenv.PrependToPath(os.Getenv("PATH"))
end
Executor->>Runner: Create runner with resolved executable + env (updatedPATH + tenv.EnvVars())
Runner-->>Executor: execution result
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
📝 Coding Plan
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 |
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@pkg/dependencies/installer.go`:
- Around line 218-225: Normalize the names before comparing in
ResolveExecutablePath: when you get binaryPath from
i.binaryPathFinder.FindBinaryPath(owner, repo, version) strip the extension from
filepath.Base(binaryPath) (use strings.TrimSuffix(..., filepath.Ext(...))) and
also strip any extension from the requested executable variable, then compare
those normalized basenames instead of comparing filepath.Base(binaryPath) ==
executable; update the comparison logic around binaryPath/executable in
installer.go and add a Windows-specific unit test (similar to
TestIsToolInstalled_DifferentBinaryName) that asserts ResolveExecutablePath
returns the .exe path when executable is provided without extension.
In `@pkg/terraform/output/executor_test.go`:
- Around line 1231-1258: The test sets a package-global toolchain config via
toolchain.SetAtmosConfig() and must restore the original config to avoid leaking
t.TempDir() into other tests; capture the original config with
toolchain.GetAtmosConfig() at the start of the test (e.g., origToolchainConfig
:= toolchain.GetAtmosConfig()) and register a t.Cleanup that restores it via
toolchain.SetAtmosConfig(origToolchainConfig) so the package-global state is
reset after the test (apply the same guard near the other occurrence at lines
~1288-1289).
In `@pkg/terraform/output/executor.go`:
- Line 406: BuildToolchainPATH currently builds a full PATH from the process
environment and you overwrite environMap["PATH"] with it, which drops any PATH
set by SetupEnvironment() (the component env section); change the flow so you
call dependencies.BuildToolchainPATH using the PATH value already in environMap
(i.e., pass environMap["PATH"] or otherwise base the toolchain prefix on
environMap after calling SetupEnvironment()), then prepend the resulting
toolchain prefix to environMap["PATH"] instead of replacing it; update the code
around the calls to SetupEnvironment, environMap, and
dependencies.BuildToolchainPATH so the toolchain entries are injected before the
existing PATH value to preserve component overrides.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 19553d29-0ed3-4ab4-aadd-530a1035d0ef
📒 Files selected for processing (6)
pkg/dependencies/installer.gopkg/dependencies/installer_test.gopkg/dependencies/resolver.gopkg/dependencies/resolver_test.gopkg/terraform/output/executor.gopkg/terraform/output/executor_test.go
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #2172 +/- ##
==========================================
+ Coverage 77.24% 77.30% +0.05%
==========================================
Files 959 960 +1
Lines 90782 91088 +306
==========================================
+ Hits 70124 70413 +289
- Misses 16574 16591 +17
Partials 4084 4084
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
… resolution Replace scattered toolchain boilerplate (resolver + installer + EnsureTools + BuildToolchainPATH + ResolveExecutablePath) with a single ToolchainEnvironment type in pkg/dependencies/. Three constructors match caller shapes: ForComponent, ForSections, ForWorkflow. Each returns an object with Resolve(command) for executable path lookup and EnvVars() for subprocess environment configuration. This fixes exec call sites that were bypassing toolchain-managed paths: - Version commands (terraform/helmfile/packer) now resolve through toolchain - IsOpenTofu detection resolves the command through toolchain before detection - AWS eks update-kubeconfig resolves "aws" through toolchain with proper env Net reduction: ~105 lines removed across callers, replaced by 2-3 line calls. Test coverage on environment.go: 92-100% across all functions. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 6
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/exec/utils.go (1)
886-892:⚠️ Potential issue | 🟠 MajorDon't drop back to
nilhere.Line 892 bypasses the new toolchain-aware resolution and falls back to the parent PATH. If the configured Terraform command resolves to an OpenTofu binary via
ToolchainEnvironment(for example through a symlink, alias, or toolchain-installed path), this branch can still misclassify it as Terraform and raise a falseterraform-config-inspecterror for valid OpenTofu syntax. Pass the current toolchain environment intoIsOpenTofu, or derive one fromconfigAndStacksInfo.StackSectionandconfigAndStacksInfo.ComponentSectionbefore detecting.Based on learnings, "command names don't reliably indicate the actual binary being executed (symlinks, aliases)."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/exec/utils.go` around lines 886 - 892, The code currently calls IsOpenTofu(&effectiveConfig, nil) which ignores the toolchain-aware resolution and can misclassify a configured Terraform command that actually resolves to an OpenTofu binary; instead derive or obtain the relevant ToolchainEnvironment from configAndStacksInfo (e.g., using the StackSection and ComponentSection or the project's toolchain resolver) and pass that toolchainEnv into IsOpenTofu (call IsOpenTofu(&effectiveConfig, toolchainEnv)) so detection considers symlinks/aliases/toolchain-installed paths when deciding whether to skip validation.
♻️ Duplicate comments (2)
pkg/dependencies/environment.go (1)
281-283:⚠️ Potential issue | 🟠 MajorStore the bare executable name here too.
On Windows this key becomes
tofu.exe/aws.exe, but callers resolve bare names liketofuandaws.Resolve()then misses the toolchain entry and falls back to the system PATH, so toolchain-installed binaries still won't resolve there.Patch sketch
- env.resolved[filepath.Base(binaryPath)] = binaryPath + base := filepath.Base(binaryPath) + env.resolved[base] = binaryPath + env.resolved[strings.TrimSuffix(base, filepath.Ext(base))] = binaryPathAs per coding guidelines, "Cross-Platform Compatibility (MANDATORY): Ensure Linux/macOS/Windows compatibility."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/dependencies/environment.go` around lines 281 - 283, The map assignment only stores the OS-specific basename (e.g., "tofu.exe") so Resolve() misses bare names; update the code that sets env.resolved (the place using filepath.Base(binaryPath)) to also store the bare executable name by deriving base := filepath.Base(binaryPath), computing bare := strings.TrimSuffix(base, filepath.Ext(base)) (guarding against empty strings), and set env.resolved[bare] = binaryPath in addition to env.resolved[base] = binaryPath so both "tofu.exe" and "tofu" resolve across platforms.internal/exec/workflow_utils.go (1)
330-333:⚠️ Potential issue | 🟠 MajorPrepend into the merged PATH instead of appending another
PATH=.
baseEnvalready carries PATH fromos.Environ()plusatmosConfig.Env.tenv.EnvVars()is built from the process PATH again, so appending it here can drop workflow/global PATH overrides and leaves duplicate PATH keys in the subprocess env. Replace the existing PATH value withtenv.PrependToPath(...)instead.Based on learnings, "non-identity steps intentionally use baseWorkflowEnv, which is constructed from the parent environment with PATH modifications for the toolchain. Avoid appending os.Environ() again; prefer documenting this behavior and testing that standard environment variables are preserved."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/exec/workflow_utils.go` around lines 330 - 333, baseEnv is currently built by merging os.Environ() and atmosConfig.Env and then appending tenv.EnvVars(), which reintroduces PATH and can override workflow/global PATH entries and produce duplicate PATH keys; instead, stop appending tenv.EnvVars() and update baseEnv's PATH entry by calling tenv.PrependToPath(...) (using the existing baseEnv, envpkg.MergeGlobalEnv, os.Environ(), atmosConfig.Env and tenv.PrependToPath symbols) so the toolchain PATH is prepended to the already-merged environment while preserving any PATH set by the workflow/global envs; remove the append of tenv.EnvVars() and add logic to replace the PATH value in baseEnv via tenv.PrependToPath to avoid duplicate PATH entries.
🧹 Nitpick comments (1)
internal/exec/terraform_detection_test.go (1)
72-72: Add one non-niltoolchain case.All of the updated call sites here still exercise
IsOpenTofu(..., nil), so the newtenv.Resolve(...)branch and resolved-command cache key never run under test. One case that drivesIsOpenTofuwith a real or test-specificToolchainEnvironmentwould lock in the behavior this PR adds.As per coding guidelines, "Every new feature must include comprehensive unit tests targeting >80% code coverage for all packages."
Also applies to: 94-108, 126-126, 154-174, 355-356, 472-473, 495-517
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/exec/terraform_detection_test.go` at line 72, Add a unit test that calls IsOpenTofu with a non-nil ToolchainEnvironment so the tenv.Resolve(...) branch and the resolved-command cache key are exercised; specifically, create a test-specific ToolchainEnvironment (or mock) that returns a determinable resolution for Resolve and pass it into IsOpenTofu(atmosConfig, yourTenv) to assert expected behavior and cache interactions, and add similar non-nil cases for the other call sites mentioned so coverage includes the tenv.Resolve path and resolved-command caching logic.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@internal/exec/aws_eks_update_kubeconfig.go`:
- Around line 251-256: The call to dependencies.ForComponent currently discards
component context and thus misses component-level tools; update the call to pass
the discovered component context from ProcessStacks by supplying
configAndStacksInfo.ComponentType, configAndStacksInfo.StackSection and
configAndStacksInfo.ComponentSection (instead of empty/ nil placeholders) so
ForComponent can resolve component-level dependencies; keep the returned tenv
and then call ExecuteShellCommand(atmosConfig, tenv.Resolve("aws"), args,
shellCommandWorkingDir, tenv.EnvVars(), dryRun, "") as before.
In `@internal/exec/terraform.go`:
- Around line 296-299: The code calls resolveAndInstallToolchainDeps(...) but
discards the returned toolchain environment (tenv) and leaves info.Command as
the bare name, causing OS lookup failures; change the call to capture the
returned tenv from resolveAndInstallToolchainDeps (when shouldProcess is true),
then call tenv.Resolve(info.Command) and assign the resolved path back to
info.Command before calling ExecuteShellCommand (or other execution paths),
ensuring you reference resolveAndInstallToolchainDeps, tenv, tenv.Resolve,
info.Command, and ExecuteShellCommand when making the change.
In `@internal/exec/workflow_utils_test.go`:
- Around line 1565-1572: The tests around ForWorkflow in workflow_utils_test.go
are nondeterministic because they accept any error and may trigger real
installs; update both test blocks that call dependencies.ForWorkflow(...) to
create a deterministic fixture by pre-creating a fake executable under the
Toolchain.InstallPath (simulate installed tools) before calling
dependencies.ForWorkflow, then assert that tenv.PATH() is non-empty and that
tenv.Resolve("terraform") (or the specific tool name used) returns the expected
path, and no longer swallow errors from ForWorkflow — fail the test if it
returns an unexpected error; apply the same change pattern to the second block
that currently mirrors this behavior.
In `@pkg/dependencies/environment_test.go`:
- Around line 186-209: The test currently succeeds even when ForWorkflow fails
to install or resolve tools, so change ForWorkflow (or overload/new helper used
by tests) to accept a ToolInstaller/PathResolver interface (e.g., an installer
interface used by ForWorkflow) and update the test to inject a mock
implementation generated with go.uber.org/mock/mockgen that simulates successful
tool installation and a fixed PATH; then assert that tenv.PATH() equals the
expected mocked value (or is non-empty) to deterministically verify the
.tool-versions handling instead of relying on real network installs. Ensure
references to ForWorkflow and the installer/path-resolution abstraction are used
so the test can stub behavior without performing network installs.
- Around line 16-82: Tests in TestToolchainEnvironment_* hardcode Unix-style
paths, PATH separators and use "sh"; update assertions to be OS-neutral by
building expected paths with filepath.Join (for e.g. the resolved tool paths)
and constructing PATH using string(os.PathListSeparator) instead of ":"; in the
Resolve "system PATH tool" case avoid using "sh"—use a platform-neutral lookup
like the current process executable (e.g., base := filepath.Base(os.Args[0]) and
exec.LookPath(base)) so Resolve("base") is expected to return an absolute path;
update assertions in TestToolchainEnvironment_Resolve,
TestToolchainEnvironment_EnvVars, and TestToolchainEnvironment_PATH to use these
changes and reference the ToolchainEnvironment.Resolve, EnvVars, and PATH
methods.
In `@pkg/dependencies/environment.go`:
- Around line 228-237: BuildToolchainPATH can return the current process PATH
when nothing changed, so avoid treating that as an augmentation: after calling
buildPATH(atmosConfig, deps) check whether toolchainPATH equals the current
process environment PATH (os.Getenv("PATH")) or equals the existing env.path
and, if so, do not set env.path (leave it nil/unchanged) so EnvVars() won't emit
a redundant "PATH="; update the block around buildPATH, BuildToolchainPATH, and
env.path assignment (referencing buildPATH variable, BuildToolchainPATH,
toolchainPATH, and env.path) to only assign when toolchainPATH is meaningfully
different.
---
Outside diff comments:
In `@internal/exec/utils.go`:
- Around line 886-892: The code currently calls IsOpenTofu(&effectiveConfig,
nil) which ignores the toolchain-aware resolution and can misclassify a
configured Terraform command that actually resolves to an OpenTofu binary;
instead derive or obtain the relevant ToolchainEnvironment from
configAndStacksInfo (e.g., using the StackSection and ComponentSection or the
project's toolchain resolver) and pass that toolchainEnv into IsOpenTofu (call
IsOpenTofu(&effectiveConfig, toolchainEnv)) so detection considers
symlinks/aliases/toolchain-installed paths when deciding whether to skip
validation.
---
Duplicate comments:
In `@internal/exec/workflow_utils.go`:
- Around line 330-333: baseEnv is currently built by merging os.Environ() and
atmosConfig.Env and then appending tenv.EnvVars(), which reintroduces PATH and
can override workflow/global PATH entries and produce duplicate PATH keys;
instead, stop appending tenv.EnvVars() and update baseEnv's PATH entry by
calling tenv.PrependToPath(...) (using the existing baseEnv,
envpkg.MergeGlobalEnv, os.Environ(), atmosConfig.Env and tenv.PrependToPath
symbols) so the toolchain PATH is prepended to the already-merged environment
while preserving any PATH set by the workflow/global envs; remove the append of
tenv.EnvVars() and add logic to replace the PATH value in baseEnv via
tenv.PrependToPath to avoid duplicate PATH entries.
In `@pkg/dependencies/environment.go`:
- Around line 281-283: The map assignment only stores the OS-specific basename
(e.g., "tofu.exe") so Resolve() misses bare names; update the code that sets
env.resolved (the place using filepath.Base(binaryPath)) to also store the bare
executable name by deriving base := filepath.Base(binaryPath), computing bare :=
strings.TrimSuffix(base, filepath.Ext(base)) (guarding against empty strings),
and set env.resolved[bare] = binaryPath in addition to env.resolved[base] =
binaryPath so both "tofu.exe" and "tofu" resolve across platforms.
---
Nitpick comments:
In `@internal/exec/terraform_detection_test.go`:
- Line 72: Add a unit test that calls IsOpenTofu with a non-nil
ToolchainEnvironment so the tenv.Resolve(...) branch and the resolved-command
cache key are exercised; specifically, create a test-specific
ToolchainEnvironment (or mock) that returns a determinable resolution for
Resolve and pass it into IsOpenTofu(atmosConfig, yourTenv) to assert expected
behavior and cache interactions, and add similar non-nil cases for the other
call sites mentioned so coverage includes the tenv.Resolve path and
resolved-command caching logic.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 2f9342bd-2bc6-4585-9c17-629830149848
📒 Files selected for processing (15)
internal/exec/aws_eks_update_kubeconfig.gointernal/exec/helmfile.gointernal/exec/packer.gointernal/exec/terraform.gointernal/exec/terraform_detection.gointernal/exec/terraform_detection_test.gointernal/exec/utils.gointernal/exec/workflow_utils.gointernal/exec/workflow_utils_test.gopkg/dependencies/environment.gopkg/dependencies/environment_test.gopkg/dependencies/installer.gopkg/dependencies/installer_test.gopkg/terraform/output/executor.gopkg/terraform/output/executor_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
- pkg/terraform/output/executor_test.go
…t downloads, improve error messages, fix cross-platform tests - Change artifact fetcher to accept any completed workflow run, not just successful ones, so build artifacts can be downloaded even when unrelated jobs fail - Pass component type and sections to ForComponent in EKS kubeconfig for proper toolchain resolution - Use tenv.Resolve for command in ExecuteTerraform to resolve toolchain paths - Fix environment.go to not set PATH when it equals system PATH - Make environment tests cross-platform (use filepath.Join, os.PathListSeparator) - Remove flaky network-dependent workflow tests - Simplify error hints to be more concise and actionable - Remove redundant authentication hints from reexec error builders Co-Authored-By: Claude Opus 4.6 <[email protected]>
When tools are installed on-demand via dependencies.tools, each tool is resolved to its absolute path per-component (since different components can declare different tool versions). The bug was that the resolved absolute path wasn't being used when invoking the binary — only the subprocess env was updated, but exec.Command resolves binaries against the parent process PATH. Also addresses CodeRabbit review feedback: pass component context to ForComponent in aws_eks, guard against redundant PATH emission, make tests OS-neutral and deterministic, and remove nondeterministic workflow tests. Co-Authored-By: Claude Opus 4.6 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 5
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
pkg/github/artifacts.go (1)
284-321:⚠️ Potential issue | 🟠 MajorCompleted-run lookup can miss a usable artifact.
The new comment says this helper finds a run that “produced artifacts”, but the loop still returns the first
Testsrun in the response without checking that. After widening the filter tocompleted, that first match can be a failed/cancelled rerun with no upload, which makes callers returnErrNoArtifactFoundeven when another completed run for the same SHA does have the artifact. Please only select a run after confirming the target artifact exists.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/github/artifacts.go` around lines 284 - 321, The loop in findCompletedWorkflowRun currently returns the first workflow run named by workflowName without verifying it actually produced artifacts; change it to iterate all runs named workflowName and for each call the ActionsService artifact-listing method (e.g. actions.ListWorkflowRunArtifacts or equivalent) for run.GetID(), check the response/artifacts total count > 0 (and handle errors via handleGitHubAPIError), and only return the workflowRunInfo for the first run that has artifacts; if no matching run with artifacts is found, return the existing ErrNoWorkflowRunFound error.
🧹 Nitpick comments (1)
pkg/github/artifacts_test.go (1)
332-366: Assert the workflow-run query options in these mocks.All of these expectations accept
gomock.Any()for*github.ListWorkflowRunsOptions, so the suite would still pass iffindCompletedWorkflowRunstopped sendingStatus: "completed"or dropped theHeadSHAfilter. Since that request shape is the behavior this change is protecting, it’s worth asserting those fields in the mock callback.As per coding guidelines: "Test Quality (MANDATORY): Test behavior, not implementation."🧪 Tighten one expectation pattern
mockActions.EXPECT(). - ListRepositoryWorkflowRuns(gomock.Any(), "owner", "repo", gomock.Any()). - Return(runs, nil, nil) + ListRepositoryWorkflowRuns(gomock.Any(), "owner", "repo", gomock.AssignableToTypeOf(&github.ListWorkflowRunsOptions{})). + DoAndReturn(func(_ context.Context, owner, repo string, opts *github.ListWorkflowRunsOptions) (*github.WorkflowRuns, *github.Response, error) { + assert.Equal(t, "abc123", opts.HeadSHA) + assert.Equal(t, "completed", opts.Status) + return runs, nil, nil + })Also applies to: 373-400, 409-442, 945-957
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/github/artifacts_test.go` around lines 332 - 366, The mock expectation is too loose because it uses gomock.Any() for the *github.ListWorkflowRunsOptions; update the expectation in TestFindCompletedWorkflowRun to assert the request shape by replacing the final gomock.Any() with gomock.AssignableToTypeOf(&github.ListWorkflowRunsOptions{}) and add a Do/DoAndReturn callback that inspects the passed *github.ListWorkflowRunsOptions (the fourth arg) and asserts opts.Status == "completed" and opts.HeadSHA == "abc123"; locate the expectation on mockActions.ListRepositoryWorkflowRuns and apply the same pattern to the other mentioned tests (around the other ranges) to ensure the Status and HeadSHA filters are validated.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@internal/exec/terraform.go`:
- Around line 59-65: Do not append tenv.EnvVars() into info.ComponentEnvList
here; instead carry the tenv value forward and remove the append so
ExecuteTerraform can merge tenv.EnvVars() into the final PATH when building the
complete environment. Concretely, stop mutating info.ComponentEnvList in this
function (remove the call that appends tenv.EnvVars()), keep returning tenv as
before, and modify ExecuteTerraform to incorporate tenv.EnvVars() only when
computing the effective PATH (merge toolchain dirs with any later PATH entries
so later sources can override but toolchain dirs are preserved).
In `@pkg/dependencies/environment.go`:
- Around line 283-284: The map env.resolved is only indexed by
filepath.Base(binaryPath), so Resolve(...) can miss matches when the configured
command is an alias or symlink; update the code that sets env.resolved (the line
using filepath.Base(binaryPath) and binaryPath) to also set
env.resolved[requestedName] = binaryPath (i.e., store the resolved path under
the requested tool/command name used by Resolve()), keeping the existing
filepath.Base entry as well so both lookup forms succeed.
In `@pkg/toolchain/pr_artifact.go`:
- Around line 623-626: The hint "CI build may be failing on this PR" is
misleading in the github.ErrNoWorkflowRunFound branch; in the
WithExplanationf/... hint chain starting at the WithExplanationf("No completed
CI run found for PR #%d", prNumber) call in pr_artifact.go, remove the
WithHint("CI build may be failing on this PR") entry so only hints about
workflow completion and fork artifact access remain; if you still want to
suggest a failing build, add that WithHint to the artifact-missing handling path
instead (the branch that reports missing artifacts).
- Around line 601-603: The three WithHint(...) messages in pr_artifact.go that
currently hardcode "brew install gh" and "export GITHUB_TOKEN=..." should be
made OS-neutral: either replace them with a single generic hint like "Install
GitHub CLI or set a GITHUB_TOKEN environment variable" and a platform-agnostic
link to GitHub token docs, or branch on runtime.GOOS inside the code that
constructs these hints (using the same WithHint call sites) to emit
Windows-specific instructions (PowerShell setx or set) vs POSIX export and an
alternative install command for Linux vs macOS; update the WithHint invocations
accordingly so the error message is accurate on Windows and non-Homebrew
systems.
In `@pkg/toolchain/sha_artifact.go`:
- Around line 219-224: The error hints in the errUtils.Build call in
sha_artifact.go (the return that starts with
errUtils.Build(errUtils.ErrToolNotFound)) are incorrect for this branch; replace
the hint "CI build may be failing for this commit" with a
trigger/visibility-focused hint such as "CI run completed but may be
inaccessible due to fork/visibility or trigger settings" (or similar), and
ensure the other hints remain (No completed CI run message, fork
artifacts/accessibility hint, and the commit URL hint) so the error points to
trigger/visibility causes rather than a failing build.
---
Outside diff comments:
In `@pkg/github/artifacts.go`:
- Around line 284-321: The loop in findCompletedWorkflowRun currently returns
the first workflow run named by workflowName without verifying it actually
produced artifacts; change it to iterate all runs named workflowName and for
each call the ActionsService artifact-listing method (e.g.
actions.ListWorkflowRunArtifacts or equivalent) for run.GetID(), check the
response/artifacts total count > 0 (and handle errors via handleGitHubAPIError),
and only return the workflowRunInfo for the first run that has artifacts; if no
matching run with artifacts is found, return the existing ErrNoWorkflowRunFound
error.
---
Nitpick comments:
In `@pkg/github/artifacts_test.go`:
- Around line 332-366: The mock expectation is too loose because it uses
gomock.Any() for the *github.ListWorkflowRunsOptions; update the expectation in
TestFindCompletedWorkflowRun to assert the request shape by replacing the final
gomock.Any() with gomock.AssignableToTypeOf(&github.ListWorkflowRunsOptions{})
and add a Do/DoAndReturn callback that inspects the passed
*github.ListWorkflowRunsOptions (the fourth arg) and asserts opts.Status ==
"completed" and opts.HeadSHA == "abc123"; locate the expectation on
mockActions.ListRepositoryWorkflowRuns and apply the same pattern to the other
mentioned tests (around the other ranges) to ensure the Status and HeadSHA
filters are validated.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: f8c868d9-bcac-438e-b1c1-1e388d8bb16a
📒 Files selected for processing (9)
internal/exec/aws_eks_update_kubeconfig.gointernal/exec/terraform.gointernal/exec/workflow_utils_test.gopkg/dependencies/environment.gopkg/github/artifacts.gopkg/github/artifacts_test.gopkg/toolchain/pr_artifact.gopkg/toolchain/sha_artifact.gopkg/version/reexec.go
💤 Files with no reviewable changes (1)
- pkg/version/reexec.go
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/exec/aws_eks_update_kubeconfig.go
Strip file extensions when storing/looking up resolved executables so
that Resolve("tofu") finds "tofu.exe" on Windows. Reduce Windows file
delay from 200ms to 50ms and retry delays from 200/500/1000ms to
50/100/200ms to cut CI runtime.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
pkg/dependencies/environment.go (1)
285-289: Consider storing resolved path under the tool name as well.Currently only the binary basename is used as the key. If the tool name differs from the binary name (e.g., tool
"opentofu"installs binary"tofu"), callingResolve("opentofu")won't find the path.Suggested fix
// Store by binary basename without extension so Resolve("tofu") works // cross-platform (e.g. binary is "tofu.exe" on Windows, lookup is "tofu"). base := filepath.Base(binaryPath) key := strings.TrimSuffix(base, filepath.Ext(base)) env.resolved[key] = binaryPath + // Also store by tool name for alias/symlink scenarios where tool name + // differs from binary name (e.g., "opentofu" → "tofu" binary). + toolKey := strings.TrimSuffix(tool, filepath.Ext(tool)) + if toolKey != key { + env.resolved[toolKey] = binaryPath + }Based on learnings: "command names don't reliably indicate the actual binary being executed (symlinks, aliases)."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/dependencies/environment.go` around lines 285 - 289, The code stores resolved binary paths only under the binary basename (key computed from binaryPath) which breaks Resolve("toolName") when the tool name differs from the binary (e.g., "opentofu" -> "tofu"); update the population logic in the environment resolver (where env.resolved is assigned) to also store the same binaryPath under the declared tool name (lookup name used by Resolve), e.g., derive the tool name from the discovered package metadata or the provided tool identifier and set env.resolved[toolName] = binaryPath in addition to the existing env.resolved[key] = binaryPath so Resolve can find by either name (ensure you handle empty/toolName == key to avoid duplicates).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@pkg/dependencies/environment.go`:
- Around line 285-289: The code stores resolved binary paths only under the
binary basename (key computed from binaryPath) which breaks Resolve("toolName")
when the tool name differs from the binary (e.g., "opentofu" -> "tofu"); update
the population logic in the environment resolver (where env.resolved is
assigned) to also store the same binaryPath under the declared tool name (lookup
name used by Resolve), e.g., derive the tool name from the discovered package
metadata or the provided tool identifier and set env.resolved[toolName] =
binaryPath in addition to the existing env.resolved[key] = binaryPath so Resolve
can find by either name (ensure you handle empty/toolName == key to avoid
duplicates).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: fef48607-2ccd-4b9b-95e4-bac2f0c89eea
📒 Files selected for processing (3)
pkg/dependencies/environment.gopkg/terraform/output/executor_test.gopkg/terraform/output/platform_windows.go
…S-neutral hints - Defer toolchain PATH injection until after all env assembly in ExecuteTerraform so toolchain dirs always take precedence over PATH entries from ComponentEnvSection or auth hooks - Store resolved binary paths under both the tool name and binary basename so aliases/symlinks are found by Resolve() - Make brew install hint conditional on macOS or brew availability, use OS-neutral wording for GITHUB_TOKEN hint Co-Authored-By: Claude Opus 4.6 <[email protected]>
There was a problem hiding this comment.
♻️ Duplicate comments (2)
pkg/toolchain/pr_artifact.go (1)
637-640:⚠️ Potential issue | 🟡 MinorThe "CI build may be failing" hint is misleading here.
This branch handles
ErrNoWorkflowRunFound, meaning no completed run exists. A failed CI run is still a completed run. This hint creates confusion about the actual error state. Consider removing it or moving it to theErrNoArtifactFoundbranch where it would fit better.Suggested fix
if errors.Is(err, github.ErrNoWorkflowRunFound) { return errUtils.Build(errUtils.ErrToolNotFound). WithExplanationf("No completed CI run found for PR #%d", prNumber). WithHint("CI workflow may not have completed yet"). - WithHint("CI build may be failing on this PR"). WithHint("Artifacts from fork PRs are not accessible"). WithHintf("Check PR status: %s", prURL). WithExitCode(1). Err() }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/toolchain/pr_artifact.go` around lines 637 - 640, In the block that constructs the error for ErrNoWorkflowRunFound (the chain calling WithExplanationf("No completed CI run found for PR #%d") and subsequent WithHint calls), remove the misleading WithHint("CI build may be failing on this PR") because a failed run would still be a completed run; alternatively move that hint into the ErrNoArtifactFound error branch where a failing build is a plausible cause. Update the code that builds the error (the chained WithExplanationf/WithHint calls) to either drop that hint or add it to the ErrNoArtifactFound branch so the hints accurately match the error condition.internal/exec/terraform.go (1)
463-467:⚠️ Potential issue | 🟠 MajorMerge the toolchain dirs into the final
PATH, don’t replace it.Appending
tenv.EnvVars()here still overwrites any earlierPATH=ininfo.ComponentEnvListwith a value built from the parent process PATH. That keeps toolchain precedence, but it also drops component/auth PATH additions entirely and can hide helper binaries those hooks rely on. Build one mergedPATH=from the effective PATH assembled so far andtenv.PrependToPath(...), then append only that entry.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/exec/terraform.go` around lines 463 - 467, The current append of tenv.EnvVars() overwrites any existing PATH entries in info.ComponentEnvList; instead compute the effective PATH from info.ComponentEnvList (extract existing PATH if present or use os.Getenv("PATH")), call tenv.PrependToPath(effectivePath) to get the toolchain-prefixed PATH, replace or append a single PATH entry with that merged value, and only append the resulting PATH env var (not the full tenv.EnvVars()) so component/auth-added PATH entries are preserved while still giving toolchain precedence.
🧹 Nitpick comments (1)
pkg/dependencies/environment.go (1)
243-251: KeepToolchainDirs()derived from the same source asPATH().
env.pathcomes frombuildPATH(...), butenv.dirsis rebuilt fromenv.resolved, andresolveBinaryPaths()explicitly skips failures. That meansPrependToPath()can emit a different toolchain prefix thanEnvVars()/PATH()for the same environment. Derivedirsfrom the ordered PATH builder result so the two APIs stay consistent.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/dependencies/environment.go` around lines 243 - 251, The toolchain dirs are being built from env.resolved but PATH() is created by buildPATH(...), causing inconsistent prefixes; instead derive env.dirs from the same ordered PATH string used by buildPATH so ToolchainDirs()/PrependToPath() match EnvVars()/PATH(). Replace the loop that populates env.dirs from env.resolved with logic that splits the built PATH (the value assigned to env.path or the string returned by buildPATH), iterate the split list in order, append each unique directory (use a seen map) into env.dirs to preserve order and deduplicate; keep the rest of resolveBinaryPaths() behavior unchanged so failures stay skipped.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@internal/exec/terraform.go`:
- Around line 463-467: The current append of tenv.EnvVars() overwrites any
existing PATH entries in info.ComponentEnvList; instead compute the effective
PATH from info.ComponentEnvList (extract existing PATH if present or use
os.Getenv("PATH")), call tenv.PrependToPath(effectivePath) to get the
toolchain-prefixed PATH, replace or append a single PATH entry with that merged
value, and only append the resulting PATH env var (not the full tenv.EnvVars())
so component/auth-added PATH entries are preserved while still giving toolchain
precedence.
In `@pkg/toolchain/pr_artifact.go`:
- Around line 637-640: In the block that constructs the error for
ErrNoWorkflowRunFound (the chain calling WithExplanationf("No completed CI run
found for PR #%d") and subsequent WithHint calls), remove the misleading
WithHint("CI build may be failing on this PR") because a failed run would still
be a completed run; alternatively move that hint into the ErrNoArtifactFound
error branch where a failing build is a plausible cause. Update the code that
builds the error (the chained WithExplanationf/WithHint calls) to either drop
that hint or add it to the ErrNoArtifactFound branch so the hints accurately
match the error condition.
---
Nitpick comments:
In `@pkg/dependencies/environment.go`:
- Around line 243-251: The toolchain dirs are being built from env.resolved but
PATH() is created by buildPATH(...), causing inconsistent prefixes; instead
derive env.dirs from the same ordered PATH string used by buildPATH so
ToolchainDirs()/PrependToPath() match EnvVars()/PATH(). Replace the loop that
populates env.dirs from env.resolved with logic that splits the built PATH (the
value assigned to env.path or the string returned by buildPATH), iterate the
split list in order, append each unique directory (use a seen map) into env.dirs
to preserve order and deduplicate; keep the rest of resolveBinaryPaths()
behavior unchanged so failures stay skipped.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: e306cdaf-e055-4065-b181-780230c85efd
📒 Files selected for processing (3)
internal/exec/terraform.gopkg/dependencies/environment.gopkg/toolchain/pr_artifact.go
Replace hardcoded Unix paths, PATH separators, and "sh" lookups with filepath.Join, os.PathListSeparator, and os.Args[0] so tests pass on Windows. Co-Authored-By: Claude Opus 4.6 <[email protected]>
The 50ms delays were too aggressive and caused terraform state file locking errors on Windows CI. Restore the original 200/500/1000ms retry delays that give Windows enough time to release file locks between sequential terraform operations. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Add ToolProvisioner interface and inject a mockgen-generated mock into the test so it no longer depends on real network installs. The test now asserts PATH() and Resolve() equal exact expected values. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Version constraints like "^1.10.0" were passed directly to the download URL, producing 404s (e.g., github.com/.../releases/download/^1.10.0/...). Add VersionLister interface and resolveConstraints() to the dependencies Installer. Before building tool specs, any constraint is resolved to the highest matching release via the GitHub releases API, then the concrete version flows through to install, PATH building, and binary lookup. Co-Authored-By: Claude Opus 4.6 <[email protected]>
The GetAvailableVersions network call had no user feedback, making the CLI appear frozen. Wrap each constraint resolution in a spinner that shows progress and the resolved version on completion. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Two fixes: - resolveBinaryPaths now converts relative paths to absolute before storing in the resolved map, preventing "no such file" errors when the install path is relative (e.g., .tools). - examples/toolchain sets command: tofu since the example uses OpenTofu, not HashiCorp Terraform. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Before this change, every `atmos terraform plan` with a constraint like `^1.10.0` hit the GitHub API to resolve it, even when a matching version was already installed locally. This added seconds of latency per run. Now resolveConstraints checks locally installed versions first via ListInstalledVersions (a fast directory scan). The network call only happens when no installed version satisfies the constraint. Also adds missing `variable "stage"` to the toolchain example mock component to suppress the OpenTofu undeclared variable warning. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Display an info message when a semver constraint is resolved from the local cache, so users see which concrete version is being used without needing a network call (e.g., "Using opentofu 1.11.5 (satisfies ^1.10.0)"). Co-Authored-By: Claude Opus 4.6 <[email protected]>
Verify the toolchain example stack configuration loads correctly: - describe component mock in dev stack - component-level tool dependencies (opentofu) present in output - terraform command set to tofu - describe stacks produces valid JSON These tests validate config parsing without requiring tool installation or network access, making them safe for CI. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Glamour's GFM linkify interprets owner/repo@version as email autolinks (e.g., [email protected] → mailto:), stripping tool names from output. The custom StrictLinkifyExtension works at goldmark level but not through glamour's rendering pipeline. Fix by wrapping tool specs in backticks (code spans are never autolinked). Also change skip messages from ui.Successf to ui.Info since skipping is informational, not a success. Add regression tests at both levels: - goldmark: extensions_test.go (passes, confirming extension works) - glamour: formatter_test.go (catches the rendering pipeline bug) Co-Authored-By: Claude Opus 4.6 <[email protected]>
…tools Tools installed via component-level dependencies.tools in stack YAML are not tracked in .tool-versions and were invisible to uninstall. The --all flag scans the install directory and removes everything found, including tools installed through dependency resolution. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…tion Transient network errors (stream cancel, connection reset, timeouts) during GetAvailableVersions now retry up to 3 times with exponential backoff. Uses hybrid approach: gates on registry.ErrHTTPRequest sentinel to avoid retrying non-HTTP errors, then string-matches for transient patterns. Co-Authored-By: Claude Opus 4.6 <[email protected]>
The --all flag addition gave UninstallCommandProvider a StandardParser, but the test still expected GetFlagsBuilder() to return nil. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ronment helpers Covers ~90 previously untested lines in pkg/dependencies to bring patch coverage above 80%. Adds tests for isConstraint, highestMatch, isRetryableHTTPError, findInstalledMatch, resolveConstraints, resolveOneConstraint, fetchAvailableVersionsWithRetry, PrependToPath, ToolchainDirs, and resolveBinaryPaths relative-to-absolute conversion. Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
These changes were released in v1.210.0-rc.0. |
|
These changes were released in v1.210.0-test.25. |
Summary
Comprehensive improvements to the toolchain subsystem covering binary path resolution, semver constraint resolution, and uninstall reliability.
Toolchain binary path resolution
exec.LookPathfailures)ToolchainEnvironmentto eliminate scattered resolution logicSemver constraint resolution
^1.10.0) to concrete versions before tool installregistry.ErrHTTPRequestsentinel, then string-matches for transient patternsUninstall improvements
@as email autolinks — backtick-wrap tool specs--allflag toatmos toolchain uninstallto remove tools installed via componentdependencies.tools(not just.tool-versions)ListAllInstalledTools()scans install directory two levels deep to discover all installed toolsTesting
examples/toolchain(describe component, show dependencies, command detection)TestForWorkflow_WithToolVersionsdeterministic with mockgenTest plan
go build ./...compiles cleanlygo test ./pkg/dependencies/... -count=1passesgo test ./pkg/toolchain/... -count=1passesgo test ./pkg/ui/... -count=1passesatmos toolchain uninstall --allremoves dependency-installed tools🤖 Generated with Claude Code