Skip to content

fix(toolchain): resolve install failures for checkov, trivy, yq, and jq - #2107

Merged
Andriy Knysh (aknysh) merged 12 commits into
mainfrom
osterman/fix-toolchain-install
Feb 26, 2026
Merged

Andriy Knysh (aknysh) merged 12 commits into
mainfrom
osterman/fix-toolchain-install

Conversation

@osterman

@osterman Erik Osterman (Cloud Posse) (osterman) commented Feb 24, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Fix 5 bugs in Aqua registry parsing and installer download logic that caused atmos toolchain install to fail for checkov, trivy, yq, and jq (only terraform worked)
  • Add regression tests using real-world Aqua registry YAML for all 4 failing tools
  • Rename findToolInLegacyRegistries → findToolInBuiltinRegistries

Root Causes

  1. versionOverride.Files missing Src field — checkov needs src: dist/checkov to locate the binary inside the archive. The anonymous struct only had Name.
  2. findMatchingOverride not stripping version prefix before semver — jq uses version_prefix: "jq-", so semver.NewVersion("jq-1.8.1") failed, silently skipping all semver constraints.
  3. buildAssetTemplateData ignoring tool.Replacements — OS/Arch values like amd64 weren't mapped to tool-specific values (X86_64 for checkov, 64bit for trivy, macos for jq).
  4. tryFallbackVersion hardcoded "v" prefix — jq fallback produced "vjq-1.8.1" instead of stripping "jq-" prefix.
  5. versionOverride struct missing Aqua fields — rosetta2, windows_arm_emulation, no_asset, supported_envs, checksum, version_prefix were silently dropped during YAML parsing.

Test plan

  • New tests using real-world Aqua registry YAML for checkov, trivy, yq, jq
  • Version prefix stripping tests for semver constraint evaluation
  • Custom prefix fallback tests in download logic
  • All existing tests continue to pass
  • go build ./pkg/toolchain/... compiles cleanly
  • Manual verification: atmos toolchain install on linux/amd64

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Per-tool version prefixes, richer registry overrides (per-env, per-OS format), Rosetta2 and Windows ARM emulation fallbacks, improved asset/binary resolution, two-pass asset template rendering, and optional GitHub-tag based version lookup.
  • Bug Fixes

    • More robust version-fallback and download fallback behavior; platform-matching and env-based overrides handle prefixed versions and emulation cases correctly.
  • Tests

    • Extensive new/regression tests for version fallback, constraint evaluation, templating, platform/env overrides, caching, and file-extension handling.
  • Docs/UX

    • Improved GitHub rate-limit error messaging with actionable hints.

Five bugs prevented toolchain install from working for most Aqua registry
tools. Only terraform worked because it doesn't use version overrides,
replacements, or custom version prefixes.

Fixes:
- versionOverride struct missing Files.Src field (checkov needs src: dist/checkov)
- versionOverride struct missing Aqua fields (rosetta2, supported_envs, etc.)
- applyVersionOverride not propagating Files, VersionPrefix, SupportedEnvs
- findMatchingOverride not stripping version prefix before semver evaluation
  (jq-1.8.1 failed semver parse, skipping all constraints)
- buildAssetTemplateData ignoring tool.Replacements for OS/Arch mapping
  (amd64 → X86_64 for checkov, amd64 → 64bit for trivy, etc.)
- tryFallbackVersion using hardcoded "v" prefix instead of tool.VersionPrefix
  (jq fallback produced "vjq-1.8.1" instead of stripping "jq-")

Also renames findToolInLegacyRegistries → findToolInBuiltinRegistries.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@github-actions github-actions Bot added the size/l Large size PR label Feb 24, 2026
@github-actions

github-actions Bot commented Feb 24, 2026 •

Copy link
Copy Markdown

Dependency Review

✅ No vulnerabilities or license issues found.

Scanned Files

  • go.mod

@coderabbitai

coderabbitai Bot commented Feb 24, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds per-tool VersionPrefix handling and HTTP fallback logic; renames legacy→builtin registry terminology; extends Aqua registry schema, templating (two-pass, Sprig), and version constraint evaluation (expr-lang); adds platform/emulation fallbacks; expands tests and adds expr dependency.

Changes

Cohort / File(s) Summary
Installer fallback & tests
pkg/toolchain/installer/download.go, pkg/toolchain/installer/download_test.go
Per-tool VersionPrefix used for tryFallbackVersion; fallback URL/stripping adjusted; added HTTP/404 and prefix regression tests and httptest scaffolding.
Installer terminology rename
pkg/toolchain/installer/installer.go
Renamed "legacy" → "builtin" across find-tool flows, logs, helper name, and metric keys.
Asset templating & installer platform
pkg/toolchain/installer/asset.go, pkg/toolchain/installer/asset_test.go, pkg/toolchain/installer/platform.go, pkg/toolchain/installer/platform_test.go
Introduce GOOS/GOARCH in template data, FormatOverrides per-OS, Rosetta2 and Windows ARM emulation fallbacks, compound-extension stripping, two-pass template rendering, sprig-based funcs, and related tests.
Override matching
pkg/toolchain/installer/override.go, pkg/toolchain/installer/override_test.go
Add Envs-based override matching (matchesOverride) that takes precedence over GOOS/GOARCH; tests for Envs-driven behavior.
Aqua registry core & tests
pkg/toolchain/registry/aqua/aqua.go, pkg/toolchain/registry/aqua/aqua_test.go, pkg/toolchain/registry/aqua/version.go, pkg/toolchain/registry/aqua/version_constraint_test.go
Major schema expansion (VersionPrefix, FormatOverrides, SupportedEnvs, Rosetta2, WindowsArmEmulation, NoAsset, Checksum, VersionSource, ErrorMessage, Files, etc.), computeSemVer, applyVersionOverride/resetByPkgType, two-pass asset resolution, sprig funcs, binary-name extraction/resolution, multi-phase resolveVersionOverrides, and extensive real-world YAML tests.
Registry public types & URL handling
pkg/toolchain/registry/registry.go, pkg/toolchain/registry/url.go
Expose new Tool/Aqua fields (FormatOverrides, VersionSource, NoAsset, Rosetta2, WindowsArmEmulation, ErrorMessage, etc.); replace prior semver constraint parsing with expr-lang evaluation and semver helper integration.
Installer helpers (extract, files)
pkg/toolchain/installer/extract.go, pkg/toolchain/installer/extract_test.go
Support two-pass rendering for file src templates referencing Asset/AssetWithoutExt; add regression test ensuring AssetWithoutExt populated for file src.
Installer template helpers
pkg/toolchain/installer/asset.go, pkg/toolchain/installer/asset_test.go
Add renderAssetTemplate, stripFileExtension; expand assetTemplateData (GOOS/GOARCH, Asset, AssetWithoutExt); implement two-pass rendering and unit tests.
Version resolution engine & deps
pkg/toolchain/registry/aqua/version.go, go.mod, NOTICE
Add getLatestTag (github_tag path), integrate expr-lang for constraint evaluation, add expr dependency and NOTICE entry, add semver helper wiring.
Misc tests & infra
pkg/toolchain/installer/installer_test.go, pkg/toolchain/registry/composite_test.go, pkg/toolchain/registry/url_test.go, pkg/toolchain/registry/*_test.go
Add many tests and test scaffolding across installer and registry to cover new behaviors, edge cases, and error paths.
GitHub errors & CLI IO
pkg/github/client.go, pkg/github/releases.go, pkg/version/reexec.go
Replace plain error strings with structured error builders for GitHub rate-limit handling and consolidate fatal error printing via helper.
Other small edits
pkg/toolchain/installer/installer.go (logs), pkg/toolchain/installer/download.go (minor adjustments)
Minor wording/flow tweaks; no public API signature changes.

Sequence Diagram(s)

sequenceDiagram
    participant User as User/CLI
    participant Installer as Installer
    participant AquaReg as AquaRegistry
    participant GitHub as GitHub API
    participant Expr as Expr Engine
    participant Template as Template Renderer

    User->>Installer: install tool@version
    Installer->>AquaReg: resolve package & version (checks VersionSource)
    AquaReg->>GitHub: fetch tags or releases (getLatestTag or releases API)
    GitHub-->>AquaReg: tags/releases
    AquaReg->>Expr: evaluate version constraint (Version, SemVer, semver funcs)
    Expr-->>AquaReg: match result
    AquaReg->>Template: build asset template data (two-pass render)
    Template-->>AquaReg: Asset, AssetWithoutExt
    AquaReg-->>Installer: asset URL and metadata
    Installer->>Installer: try download (fallback using per-tool VersionPrefix on 404)
    Installer-->>User: install result
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • aknysh
  • johncblandii
🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 67.80% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly summarizes the main fix: resolving install failures for four specific tools (checkov, trivy, yq, jq) by addressing root causes in Aqua registry parsing and installer logic.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch osterman/fix-toolchain-install

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

Caution

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

⚠️ Outside diff range comments (1)
pkg/toolchain/registry/aqua/aqua.go (1)

206-231: ⚠️ Potential issue | 🟠 Major

New override fields aren't applied to the tool.

Rosetta2, WindowsArmEmulation, NoAsset, and Checksum were added to versionOverride (lines 200–203), but applyVersionOverride only copies Asset, Format, VersionPrefix, Files, SupportedEnvs, Replacements, and Overrides. Since registry.Tool doesn't expose the new fields, any version override specifying them will be silently ignored. Either add these fields to Tool and wire them through the override function, or remove them from versionOverride if they're not meant for version-level configuration.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/registry/aqua/aqua.go` around lines 206 - 231,
applyVersionOverride currently copies only Asset/URL, Format, VersionPrefix,
Files, SupportedEnvs, Replacements, and Overrides from versionOverride into
registry.Tool, so new fields Rosetta2, WindowsArmEmulation, NoAsset, and
Checksum on versionOverride are ignored: add corresponding fields to the
registry.Tool struct (Rosetta2, WindowsArmEmulation, NoAsset, Checksum) and
update applyVersionOverride to set tool.Rosetta2 = override.Rosetta2,
tool.WindowsArmEmulation = override.WindowsArmEmulation, tool.NoAsset =
override.NoAsset, and tool.Checksum = override.Checksum (or remove the fields
from versionOverride if they aren’t intended to be propagated) so overrides are
correctly applied.
🧹 Nitpick comments (1)
pkg/toolchain/installer/download_test.go (1)

270-321: Prefer a table‑driven test for prefix toggling.
The same fallback logic is repeated across four subtests; a table‑driven test would reduce duplication and align with the project’s test style.

♻️ Suggested refactor
 func TestVersionFallbackLogic(t *testing.T) {
-	t.Run("adds v prefix when missing", func(t *testing.T) {
-		version := "1.0.0"
-		prefix := VersionPrefix // "v"
-		var fallbackVersion string
-		if strings.HasPrefix(version, prefix) {
-			fallbackVersion = strings.TrimPrefix(version, prefix)
-		} else {
-			fallbackVersion = prefix + version
-		}
-		assert.Equal(t, "v1.0.0", fallbackVersion)
-	})
-	...
+	tests := []struct {
+		name     string
+		version  string
+		prefix   string
+		expected string
+	}{
+		{name: "adds v prefix when missing", version: "1.0.0", prefix: VersionPrefix, expected: "v1.0.0"},
+		{name: "removes v prefix when present", version: "v1.0.0", prefix: VersionPrefix, expected: "1.0.0"},
+		{name: "custom prefix jq- strips correctly", version: "jq-1.8.1", prefix: "jq-", expected: "1.8.1"},
+		{name: "custom prefix jq- adds when missing", version: "1.8.1", prefix: "jq-", expected: "jq-1.8.1"},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			var fallbackVersion string
+			if strings.HasPrefix(tt.version, tt.prefix) {
+				fallbackVersion = strings.TrimPrefix(tt.version, tt.prefix)
+			} else {
+				fallbackVersion = tt.prefix + tt.version
+			}
+			assert.Equal(t, tt.expected, fallbackVersion)
+		})
+	}
 }
As per coding guidelines, "Use table-driven tests for testing multiple scenarios in Go."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/installer/download_test.go` around lines 270 - 321, Refactor
TestVersionFallbackLogic into a table-driven test: create a slice of test cases
each with fields name, version, prefix (use VersionPrefix for the default
cases), and want; replace the four duplicated subtests with a single loop that
calls t.Run(tc.name, func(t *testing.T) { compute fallbackVersion using the
existing logic (strings.HasPrefix/TrimPrefix or prefix+version) and
assert.Equal(t, tc.want, fallbackVersion) }); ensure you include the jq- prefix
cases and descriptive names and remove the duplicated blocks for "adds v prefix
when missing", "removes v prefix when present", "custom prefix jq- strips
correctly", and "custom prefix jq- adds when missing".
🤖 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/toolchain/registry/aqua/aqua_test.go`:
- Around line 1326-1336: Update the comment lines in the "Real-world registry
YAML tests" block so each sentence ends with a period to satisfy the godot
linter; specifically edit the header and the descriptive comments immediately
above TestResolveVersionOverrides_RealCheckovPattern (references: the block
surrounding TestResolveVersionOverrides_RealCheckovPattern and the "These tests
use EXACT real-world Aqua registry YAML..." line) to append missing trailing
periods on each comment sentence.
- Around line 1851-1914: The test currently strips tt.prefix for every case but
production only strips prefixes when the constraint uses semver(); in
TestEvaluateVersionConstraint_WithVersionPrefix update the setup so you only
TrimPrefix when the constraint begins with "semver(" (or otherwise detects a
semver constraint) before calling evaluateVersionConstraint, and change the
"Version == compares full version including prefix" case expected value to true
so it asserts against the full version; ensure you reference the test function
TestEvaluateVersionConstraint_WithVersionPrefix and the helper
evaluateVersionConstraint when making the change.

In `@pkg/toolchain/registry/aqua/aqua.go`:
- Around line 336-338: The comment above findMatchingOverride is missing a
trailing period; update the comment sentence "Following Aqua's behavior, the
version prefix is stripped before semver evaluation but preserved for Version ==
comparisons" to end with a period so godot passes; locate the comment block on
function findMatchingOverride in aqua.go and add the period to that sentence.
- Around line 188-204: The ChecksumConfig type in
pkg/toolchain/registry/aqua/aqua.go is missing fields (asset, cosign with nested
bundle, and other checksum metadata) and applyVersionOverride() does not
propagate override.Checksum into tool.Checksum; extend the ChecksumConfig struct
used by versionOverride to include Asset, Cosign (with nested Bundle and
relevant fields) and any other checksum metadata present in real Aqua YAML, then
update applyVersionOverride() to copy override.Checksum into tool.Checksum when
override.Checksum is non-empty (ensuring any existing tool.Checksum is replaced
or merged according to existing merge semantics) so version-specific checksum
configuration is applied during resolution.

---

Outside diff comments:
In `@pkg/toolchain/registry/aqua/aqua.go`:
- Around line 206-231: applyVersionOverride currently copies only Asset/URL,
Format, VersionPrefix, Files, SupportedEnvs, Replacements, and Overrides from
versionOverride into registry.Tool, so new fields Rosetta2, WindowsArmEmulation,
NoAsset, and Checksum on versionOverride are ignored: add corresponding fields
to the registry.Tool struct (Rosetta2, WindowsArmEmulation, NoAsset, Checksum)
and update applyVersionOverride to set tool.Rosetta2 = override.Rosetta2,
tool.WindowsArmEmulation = override.WindowsArmEmulation, tool.NoAsset =
override.NoAsset, and tool.Checksum = override.Checksum (or remove the fields
from versionOverride if they aren’t intended to be propagated) so overrides are
correctly applied.

---

Nitpick comments:
In `@pkg/toolchain/installer/download_test.go`:
- Around line 270-321: Refactor TestVersionFallbackLogic into a table-driven
test: create a slice of test cases each with fields name, version, prefix (use
VersionPrefix for the default cases), and want; replace the four duplicated
subtests with a single loop that calls t.Run(tc.name, func(t *testing.T) {
compute fallbackVersion using the existing logic (strings.HasPrefix/TrimPrefix
or prefix+version) and assert.Equal(t, tc.want, fallbackVersion) }); ensure you
include the jq- prefix cases and descriptive names and remove the duplicated
blocks for "adds v prefix when missing", "removes v prefix when present",
"custom prefix jq- strips correctly", and "custom prefix jq- adds when missing".

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 8fdf9b6 and 3bf30fc.

📒 Files selected for processing (5)
  • pkg/toolchain/installer/download.go
  • pkg/toolchain/installer/download_test.go
  • pkg/toolchain/installer/installer.go
  • pkg/toolchain/registry/aqua/aqua.go
  • pkg/toolchain/registry/aqua/aqua_test.go

Comment thread pkg/toolchain/registry/aqua/aqua.go Resolved
Comment thread pkg/toolchain/registry/aqua/aqua.go Resolved
@osterman Erik Osterman (Cloud Posse) (osterman) added the patch A minor, backward compatible change label Feb 24, 2026
…platform matching, and template rendering

Phase 2 of the aqua upstream parity audit. Aligns our implementation with
aquaproj/aqua behavior for version constraint evaluation, platform override
matching, format overrides, template variable rendering, and semver comparison.

Key changes:
- Fix version override resolution order to match upstream algorithm (B3)
- Split Version/SemVer template variables for correct prefix stripping (B2)
- Port upstream semver compare() using hashicorp/go-version (B1)
- Add "all" keyword support to isPlatformMatch (B4)
- Remove arm64-replacement curve fit from Rosetta2 fallback (B5)
- Add format_overrides support for per-OS archive format selection (H1)
- Add Envs field to Override for platform matching via isPlatformMatch (H2)
- Add Type/RepoOwner/RepoName/ErrorMessage to version overrides (H3-H6)
- Implement resetByPkgType for type-change field cleanup (H3-H6)
- Add two-pass template rendering for Asset/AssetWithoutExt variables (H7)
- Support version_source: github_tag via Tags API (H8)
- Unify URLRegistry constraint evaluation with expr-lang (M7)
- Add NoAsset, VersionSource fields to registry types (Medium)

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@github-actions github-actions Bot added size/xl Extra large size PR and removed size/l Large size PR labels Feb 24, 2026
@mergify

mergify Bot commented Feb 24, 2026

Copy link
Copy Markdown
Contributor

Warning

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

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

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

Caution

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

⚠️ Outside diff range comments (2)
pkg/toolchain/registry/aqua/aqua.go (2)

190-269: ⚠️ Potential issue | 🔴 Critical

no_asset is parsed on version overrides but never applied to registry.Tool.NoAsset.

versionOverride includes NoAsset, and registry.Tool has NoAsset, but applyVersionOverride() never propagates it. That can cause downloads to be attempted for versions explicitly marked no_asset: true.

Proposed fix
 func applyVersionOverride(tool *registry.Tool, override *versionOverride, version string) {
@@
 	if override.WindowsArmEmulation {
 		tool.WindowsArmEmulation = true
 	}
+	if override.NoAsset {
+		tool.NoAsset = true
+	}
 	if override.ErrorMessage != "" {
 		tool.ErrorMessage = override.ErrorMessage
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/registry/aqua/aqua.go` around lines 190 - 269, The
versionOverride.NoAsset field is parsed but never applied; update
applyVersionOverride to propagate NoAsset like the other additive flags: inside
applyVersionOverride, add a check if override.NoAsset { tool.NoAsset = true } so
versions marked no_asset: true prevent asset downloads while preserving existing
true values when override is false. Target symbols: versionOverride.NoAsset,
registry.Tool.NoAsset, applyVersionOverride.

321-405: ⚠️ Potential issue | 🟠 Major

Reconstruct full version with prefix before evaluating constraints.

When GetLatestVersion() uses the github_tag path (line 79), it returns a prefix-stripped version. This prefix-less version then flows into resolveVersionOverrides(), which passes it directly to evaluateVersionConstraint(). However, evaluateVersionConstraint() expects the full version including any prefix (per its docstring), and constraints like Version == "jq-1.5rc1" or Version == "v0.20.0" won't match against a stripped version like "1.5rc1" or "0.20.0".

Add the prefix back before evaluating:

Proposed fix
 func (ar *AquaRegistry) resolveVersionOverrides(sourceURL, version string) (*registry.Tool, error) {
@@
-	// Compute SemVer (prefix-stripped version) for constraint evaluation.
-	sv := computeSemVer(version, pkgDef.VersionPrefix)
+	// Reconstruct full version with prefix, then compute SemVer for constraint evaluation.
+	fullVersion := version
+	if pkgDef.VersionPrefix != "" && !strings.HasPrefix(fullVersion, pkgDef.VersionPrefix) {
+		fullVersion = pkgDef.VersionPrefix + fullVersion
+	}
+	sv := computeSemVer(fullVersion, pkgDef.VersionPrefix)
@@
-	matches, err := evaluateVersionConstraint(pkgDef.VersionConstraint, version, sv)
+	matches, err := evaluateVersionConstraint(pkgDef.VersionConstraint, fullVersion, sv)
@@
-		voSV := computeSemVer(version, vp)
+		voFullVersion := version
+		if vp != "" && !strings.HasPrefix(voFullVersion, vp) {
+			voFullVersion = vp + voFullVersion
+		}
+		voSV := computeSemVer(voFullVersion, vp)
@@
-		m, constraintErr := evaluateVersionConstraint(vo.VersionConstraint, version, voSV)
+		m, constraintErr := evaluateVersionConstraint(vo.VersionConstraint, voFullVersion, voSV)

Also applies to the version override loop (lines 407–414).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/registry/aqua/aqua.go` around lines 321 - 405, Summary:
evaluateVersionConstraint expects the full version including any prefix, but
resolveVersionOverrides currently passes a prefix-stripped version. Fix: in
resolveVersionOverrides (function resolveVersionOverrides) reconstruct the full
version string before calling evaluateVersionConstraint for both the top-level
check and each override: compute fullVersion := version and if
pkgDef.VersionPrefix (or per-override vp) is non-empty and not already present,
prefix it (e.g., fullVersion = vp + version), then call
evaluateVersionConstraint(pkgDef.VersionConstraint, fullVersion, sv) for the
top-level case and evaluateVersionConstraint(vo.VersionConstraint,
fullOverrideFullVersion, voSV) inside the VersionOverrides loop; keep
computeSemVer (computeSemVer) and applyVersionOverride unchanged, only change
the passed-in version argument to include the prefix.
♻️ Duplicate comments (2)
pkg/toolchain/registry/registry.go (1)

251-284: Checksum fields are now present, but ChecksumConfig still won’t preserve nested YAML (cosign/bundle/asset).

If you intend to consume/persist those fields, ChecksumConfig needs to model them (or store raw YAML) — otherwise they’ll be silently dropped on unmarshal.

#!/bin/bash
set -euo pipefail

# Find whether checksum metadata is used downstream.
rg -nP '\bChecksumConfig\b|\.Checksum\b' --type=go

Also applies to: 307-326

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/registry/registry.go` around lines 251 - 284, The AquaPackage
struct includes a Checksum field of type ChecksumConfig but ChecksumConfig does
not model the nested YAML keys (cosign/bundle/asset), so those nested fields
will be dropped on unmarshal; update the ChecksumConfig type to either (a) add
explicit fields for the nested structures (e.g., Cosign, Bundle, Asset) matching
the YAML shape or (b) change ChecksumConfig to hold raw YAML/json (e.g.,
map[string]interface{} or yaml.Node) to preserve arbitrary nested content, and
update any uses of ChecksumConfig (search for symbol ChecksumConfig and
references like .Checksum) to handle the new structure accordingly.
pkg/toolchain/registry/aqua/aqua_test.go (1)

1373-1379: Godot: section header/comments still missing trailing periods.

This was previously flagged; it still looks unfixed in the current snapshot.

As per coding guidelines, "All comments must end with periods (enforced by godot linter).".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/registry/aqua/aqua_test.go` around lines 1373 - 1379, The
comment block titled "Real-world registry YAML tests" (the multi-line section
header containing lines like "Real-world registry YAML tests" and the
explanatory paragraph starting "These tests use EXACT real-world Aqua registry
YAML...") is missing trailing periods; update each sentence in that
header/comment block to end with a period to comply with the godot linter (e.g.,
change "Real-world registry YAML tests" -> "Real-world registry YAML tests." and
ensure the following lines such as "These tests use EXACT real-world Aqua
registry YAML with all the fields that tools actually use (rosetta2,
windows_arm_emulation, no_asset, checksum with nested cosign, supported_envs,
etc.) to verify our parser handles them correctly." end with a period). Ensure
every comment sentence in that block (including short headings and list-like
fragments) ends with a period.
🧹 Nitpick comments (4)
pkg/toolchain/installer/asset_test.go (1)

816-835: Duplicate TestStripFileExtension exists in pkg/toolchain/registry/aqua/aqua_test.go.

The aqua package's version has additional cases (pkg, multiple dots). Consider either consolidating into one location or ensuring both stay in sync. Low priority — just a heads-up.

#!/bin/bash
# Check for duplicate TestStripFileExtension tests across the codebase.
rg -n "func TestStripFileExtension" --type=go
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/installer/asset_test.go` around lines 816 - 835, There are
duplicate tests named TestStripFileExtension (testing stripFileExtension) in two
packages which can drift out of sync; decide whether to consolidate into a
single shared test or mirror cases. Either remove the duplicate in one package
and import the shared test helper, or extend the installer asset_test.go cases
to match the aqua/aqua_test.go cases (add "pkg" and "multiple dots" scenarios)
and keep both tests updated; update references to TestStripFileExtension and
stripFileExtension accordingly so both packages cover the same inputs.
pkg/toolchain/installer/override.go (1)

25-37: Include override.Envs in the debug log for env-based matches.

When an override matches via Envs, override.GOOS/GOARCH may be empty, so the current debug log is hard to interpret.

Proposed tweak
 			log.Debug("Applied platform override",
 				"goos", goos,
 				"goarch", goarch,
 				"overrideGOOS", override.GOOS,
 				"overrideGOARCH", override.GOARCH,
+				"overrideEnvs", override.Envs,
 				"newAsset", tool.Asset,
 				"newFormat", tool.Format)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/installer/override.go` around lines 25 - 37, The debug log
inside the loop over tool.Overrides (when matchesOverride returns true and
applyOverride is called) omits override.Envs, which makes env-based overrides
unclear; update the log.Debug call in that block to include "overrideEnvs",
override.Envs (alongside override.GOOS and override.GOARCH and the
newAsset/newFormat fields) so env matches are visible in logs when GOOS/GOARCH
are empty.
pkg/toolchain/registry/aqua/aqua_test.go (2)

2099-2323: Good coverage on format_overrides / resetByPkgType / asset templating helpers; consider splitting for readability.

This file is already very large, and the inline YAML blocks make it harder to navigate. Moving the “real-world YAML” strings into testdata/ and/or splitting into additional *_test.go files would help long-term.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/registry/aqua/aqua_test.go` around lines 2099 - 2323, The test
file pkg/toolchain/registry/aqua/aqua_test.go is very large and contains inline
YAML and many unrelated tests; split it for readability by moving the large
inline YAML blocks (used in TestResolveVersionOverrides_FormatOverrides) into
separate files under testdata (e.g., registry_format_overrides.yaml) and split
groups of tests into focused test files (e.g.,
resolve_version_overrides_test.go, version_override_apply_test.go,
asset_template_helpers_test.go), updating the tests that reference registryYAML
to read from testdata; keep test helpers (stripFileExtension,
executeAssetTemplate, renderTemplate), and test names
(TestResolveVersionOverrides_FormatOverrides,
TestApplyVersionOverride_TypeChange, TestResetByPkgType, TestStripFileExtension,
TestExecuteAssetTemplate_AssetWithoutExt) intact so the logic and assertions
remain unchanged while only relocating large fixtures and reorganizing tests
across files.

388-429: Strengthen the Sprig function test to assert the transformation, not just “contains tool-”.

The title / upper cases currently don’t prove the Sprig funcs are doing anything beyond rendering without error.

Possible direction
 		{
 			name:     "sprig title function",
 			asset:    "tool-{{title .OS}}-{{.Arch}}.tar.gz",
-			contains: "tool-",
+			contains: "tool-",
 		},
@@
 			url, err := ar.BuildAssetURL(tool, "1.0.0")
 			assert.NoError(t, err)
-			assert.Contains(t, url, tt.contains)
+			assert.Contains(t, url, tt.contains)
+			// Optional: assert the expected casing for upper/title based on getOS().
 		})
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/registry/aqua/aqua_test.go` around lines 388 - 429, The test
TestAquaRegistry_BuildAssetURL_SprigFunctions only checks a generic "tool-"
substring; update each case to set the tool fields used by the template
(populate Tool.OS and Tool.RepoName) and assert the concrete transformed result
from ar.BuildAssetURL rather than a vague contains; for example set OS to
"linux" for the title/upper cases and assert the resulting URL contains
"tool-Linux-" for the title case and "tool-LINUX-" for the upper case, and keep
RepoName "TOOL" (or set explicitly) for the lower case and assert it contains
"tool-tool-1.0.0.tar.gz"; modify TestAquaRegistry_BuildAssetURL_SprigFunctions
to create registry.Tool with these OS/RepoName values and compare the exact
expected substrings returned by ar.BuildAssetURL.
🤖 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/toolchain/registry/aqua/aqua.go`:
- Around line 716-738: Update the comment inside the executeAssetTemplate
function: change the second-pass comment that currently ends with a comma ("//
Pass 2: If the template references {{.Asset}} or {{.AssetWithoutExt}},") to end
with a period instead ("// Pass 2: If the template references {{.Asset}} or
{{.AssetWithoutExt}}."). This is purely a punctuation fix to satisfy the godot
linter; no code logic changes to executeAssetTemplate, renderTemplate, or
buildAssetTemplateData are needed.
- Around line 693-714: The Sprig function map returned by assetTemplateFuncs()
currently includes dangerous OS helpers; after calling sprig.TxtFuncMap() remove
unsafe keys from the funcs map (e.g. "env", "expandenv", "getHostByName" and any
other OS/network helpers you deem risky) before returning it so remote registry
templates cannot access environment or host-resolution data; locate the
assetTemplateFuncs function and the local variable funcs (result of
sprig.TxtFuncMap()) and delete these map entries while keeping the Aqua-specific
overrides intact.

In `@pkg/toolchain/registry/aqua/version.go`:
- Around line 20-23: Update the comment lines in the doc blocks so every
sentence ends with a period to satisfy the godot linter; specifically edit the
comment above the GetLatestVersion method in AquaRegistry (and the other
multi-line comment block later in the file around the bottom of version.go) to
add trailing periods to each line/sentence while preserving wording and
formatting.

In `@pkg/toolchain/registry/registry.go`:
- Around line 205-212: The comment on the VersionPrefix field (VersionPrefix
string `yaml:"version_prefix"`) is inaccurate — runtime currently treats an
empty prefix in some code paths rather than defaulting to "v"; fix this by
either updating the comment to state that the default is empty/no implicit
prefix, or implement a real default at load-time: set VersionPrefix = "v" during
registry parsing/unmarshalling (add an UnmarshalYAML method on the registry/tool
struct or assign the default in the registry load/ParseRegistry/LoadRegistry
function) and ensure resolution code that consumes VersionPrefix (the version
resolution/path-building logic) uses the canonical value; pick one approach and
make the comment match the implemented behavior.

---

Outside diff comments:
In `@pkg/toolchain/registry/aqua/aqua.go`:
- Around line 190-269: The versionOverride.NoAsset field is parsed but never
applied; update applyVersionOverride to propagate NoAsset like the other
additive flags: inside applyVersionOverride, add a check if override.NoAsset {
tool.NoAsset = true } so versions marked no_asset: true prevent asset downloads
while preserving existing true values when override is false. Target symbols:
versionOverride.NoAsset, registry.Tool.NoAsset, applyVersionOverride.
- Around line 321-405: Summary: evaluateVersionConstraint expects the full
version including any prefix, but resolveVersionOverrides currently passes a
prefix-stripped version. Fix: in resolveVersionOverrides (function
resolveVersionOverrides) reconstruct the full version string before calling
evaluateVersionConstraint for both the top-level check and each override:
compute fullVersion := version and if pkgDef.VersionPrefix (or per-override vp)
is non-empty and not already present, prefix it (e.g., fullVersion = vp +
version), then call evaluateVersionConstraint(pkgDef.VersionConstraint,
fullVersion, sv) for the top-level case and
evaluateVersionConstraint(vo.VersionConstraint, fullOverrideFullVersion, voSV)
inside the VersionOverrides loop; keep computeSemVer (computeSemVer) and
applyVersionOverride unchanged, only change the passed-in version argument to
include the prefix.

---

Duplicate comments:
In `@pkg/toolchain/registry/aqua/aqua_test.go`:
- Around line 1373-1379: The comment block titled "Real-world registry YAML
tests" (the multi-line section header containing lines like "Real-world registry
YAML tests" and the explanatory paragraph starting "These tests use EXACT
real-world Aqua registry YAML...") is missing trailing periods; update each
sentence in that header/comment block to end with a period to comply with the
godot linter (e.g., change "Real-world registry YAML tests" -> "Real-world
registry YAML tests." and ensure the following lines such as "These tests use
EXACT real-world Aqua registry YAML with all the fields that tools actually use
(rosetta2, windows_arm_emulation, no_asset, checksum with nested cosign,
supported_envs, etc.) to verify our parser handles them correctly." end with a
period). Ensure every comment sentence in that block (including short headings
and list-like fragments) ends with a period.

In `@pkg/toolchain/registry/registry.go`:
- Around line 251-284: The AquaPackage struct includes a Checksum field of type
ChecksumConfig but ChecksumConfig does not model the nested YAML keys
(cosign/bundle/asset), so those nested fields will be dropped on unmarshal;
update the ChecksumConfig type to either (a) add explicit fields for the nested
structures (e.g., Cosign, Bundle, Asset) matching the YAML shape or (b) change
ChecksumConfig to hold raw YAML/json (e.g., map[string]interface{} or yaml.Node)
to preserve arbitrary nested content, and update any uses of ChecksumConfig
(search for symbol ChecksumConfig and references like .Checksum) to handle the
new structure accordingly.

---

Nitpick comments:
In `@pkg/toolchain/installer/asset_test.go`:
- Around line 816-835: There are duplicate tests named TestStripFileExtension
(testing stripFileExtension) in two packages which can drift out of sync; decide
whether to consolidate into a single shared test or mirror cases. Either remove
the duplicate in one package and import the shared test helper, or extend the
installer asset_test.go cases to match the aqua/aqua_test.go cases (add "pkg"
and "multiple dots" scenarios) and keep both tests updated; update references to
TestStripFileExtension and stripFileExtension accordingly so both packages cover
the same inputs.

In `@pkg/toolchain/installer/override.go`:
- Around line 25-37: The debug log inside the loop over tool.Overrides (when
matchesOverride returns true and applyOverride is called) omits override.Envs,
which makes env-based overrides unclear; update the log.Debug call in that block
to include "overrideEnvs", override.Envs (alongside override.GOOS and
override.GOARCH and the newAsset/newFormat fields) so env matches are visible in
logs when GOOS/GOARCH are empty.

In `@pkg/toolchain/registry/aqua/aqua_test.go`:
- Around line 2099-2323: The test file pkg/toolchain/registry/aqua/aqua_test.go
is very large and contains inline YAML and many unrelated tests; split it for
readability by moving the large inline YAML blocks (used in
TestResolveVersionOverrides_FormatOverrides) into separate files under testdata
(e.g., registry_format_overrides.yaml) and split groups of tests into focused
test files (e.g., resolve_version_overrides_test.go,
version_override_apply_test.go, asset_template_helpers_test.go), updating the
tests that reference registryYAML to read from testdata; keep test helpers
(stripFileExtension, executeAssetTemplate, renderTemplate), and test names
(TestResolveVersionOverrides_FormatOverrides,
TestApplyVersionOverride_TypeChange, TestResetByPkgType, TestStripFileExtension,
TestExecuteAssetTemplate_AssetWithoutExt) intact so the logic and assertions
remain unchanged while only relocating large fixtures and reorganizing tests
across files.
- Around line 388-429: The test TestAquaRegistry_BuildAssetURL_SprigFunctions
only checks a generic "tool-" substring; update each case to set the tool fields
used by the template (populate Tool.OS and Tool.RepoName) and assert the
concrete transformed result from ar.BuildAssetURL rather than a vague contains;
for example set OS to "linux" for the title/upper cases and assert the resulting
URL contains "tool-Linux-" for the title case and "tool-LINUX-" for the upper
case, and keep RepoName "TOOL" (or set explicitly) for the lower case and assert
it contains "tool-tool-1.0.0.tar.gz"; modify
TestAquaRegistry_BuildAssetURL_SprigFunctions to create registry.Tool with these
OS/RepoName values and compare the exact expected substrings returned by
ar.BuildAssetURL.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 3bf30fc and 14bf1eb.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (14)
  • NOTICE
  • go.mod
  • pkg/toolchain/installer/asset.go
  • pkg/toolchain/installer/asset_test.go
  • pkg/toolchain/installer/override.go
  • pkg/toolchain/installer/override_test.go
  • pkg/toolchain/installer/platform.go
  • pkg/toolchain/installer/platform_test.go
  • pkg/toolchain/registry/aqua/aqua.go
  • pkg/toolchain/registry/aqua/aqua_test.go
  • pkg/toolchain/registry/aqua/version.go
  • pkg/toolchain/registry/aqua/version_constraint_test.go
  • pkg/toolchain/registry/registry.go
  • pkg/toolchain/registry/url.go

Comment thread pkg/toolchain/registry/aqua/aqua.go Resolved
Comment thread pkg/toolchain/registry/aqua/aqua.go Resolved
Comment thread pkg/toolchain/registry/aqua/version.go Resolved
Comment thread pkg/toolchain/registry/registry.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

♻️ Duplicate comments (2)
pkg/toolchain/registry/aqua/aqua_test.go (1)

1373-1378: Godot: trailing period missing on section header comment.

Line 1374 // Real-world registry YAML tests lacks a trailing period, which will fail the godot linter.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/registry/aqua/aqua_test.go` around lines 1373 - 1378, The
comment header "// Real-world registry YAML tests" in aqua_test.go is missing a
trailing period and fails the godot linter; update that comment (the header line
containing the text "Real-world registry YAML tests") to end with a period ("//
Real-world registry YAML tests.") so the linter is satisfied.
pkg/toolchain/registry/aqua/aqua.go (1)

190-211: ChecksumConfig still incomplete — checksum.asset, cosign.bundle dropped during parsing.

The trivy test YAML includes checksum.asset, checksum.cosign.bundle, and checksum.cosign.opts, but registry.ChecksumConfig only has Type, URL, and Algorithm. These fields are silently dropped. Not blocking since checksums aren't consumed downstream yet, but tracking.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/registry/aqua/aqua.go` around lines 190 - 211, The
registry.ChecksumConfig struct is missing fields parsed from YAML
(checksum.asset, checksum.cosign.bundle, checksum.cosign.opts), so update the
struct definition used by versionOverride (registry.ChecksumConfig) to include
Asset string `yaml:"asset"`, CosignBundle string `yaml:"cosign.bundle"` (or
nested Cosign struct with Bundle and Opts and appropriate yaml tags) and
CosignOpts []string `yaml:"cosign.opts"` so those values are not dropped during
Unmarshal; keep the existing Type/URL/Algorithm fields and ensure yaml tags
match the YAML keys, then run/adjust any tests that assert checksum parsing to
verify the new fields are populated.
🧹 Nitpick comments (7)
pkg/toolchain/registry/url.go (2)

460-502: compareSemver and evaluateSemverOp are duplicated with aqua/version.go.

The compareSemver and evaluateSemverOp functions here are nearly identical to compareSemver and evaluateOp in aqua/version.go. The aqua version is a superset (adds isCommitHash guard). Consider extracting these into the parent registry package to avoid drift between the two copies.

Not blocking — fine to defer to a follow-up.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/registry/url.go` around lines 460 - 502, The two semver helpers
(compareSemver and evaluateSemverOp) are duplicated; extract them into a single
shared implementation in the parent registry package and have callers reuse it:
move the logic into a new registry-level function (e.g., registry.CompareSemver)
that incorporates the superset behavior from aqua/version.go (including the
isCommitHash guard/evaluateOp semantics), replace local calls to compareSemver
and evaluateSemverOp in url.go with the shared registry function, and remove the
duplicate functions to avoid divergence.

442-455: Consider adding expr.AsBool() for compile-time type safety.

The Aqua version in aqua/version.go (line 292) uses expr.Compile(constraint, expr.Env(env), expr.AsBool()) which enforces boolean return type at compile time. Here you do a manual type assertion at lines 452-455 instead. Not broken, but inconsistent.

Suggested fix
-	program, err := expr.Compile(constraint, expr.Env(env))
+	program, err := expr.Compile(constraint, expr.Env(env), expr.AsBool())

With AsBool(), the manual result.(bool) assertion at lines 452-455 becomes redundant (expr guarantees a bool), but keeping it as a safety net is fine.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/registry/url.go` around lines 442 - 455, The compile/run block
using expr.Compile(constraint, expr.Env(env)) should include expr.AsBool() to
enforce boolean return at compile time (mirroring aqua/version.go); update the
expr.Compile call to expr.Compile(constraint, expr.Env(env), expr.AsBool()) so
expr.Run(program, env) will always produce a bool, and then remove or optionally
keep the manual type assertion of output to bool (the explicit result, ok check
in the current code becomes redundant). Ensure you reference the same variables:
constraint, env, program, output/result and adjust error handling accordingly.
pkg/toolchain/installer/asset.go (2)

193-212: Aqua-specific template function argument order is intentionally reversed from Sprig.

Worth a brief inline comment noting that trimPrefix(pfx, s), trimSuffix(suffix, s), and replace(old, new, s) have reversed arg order compared to Sprig's equivalents. This prevents a future contributor from "fixing" what looks like a bug.

✏️ Suggested comment
+	// Aqua-specific overrides: argument order differs from Sprig
+	// (Aqua: trimPrefix(prefix, str), Sprig: trimPrefix(str, prefix)).
 	funcs["trimPrefix"] = func(pfx, s string) string {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/installer/asset.go` around lines 193 - 212, Add a short inline
note inside assetTemplateFuncs() explaining that the Aqua-specific wrapper
functions (funcs["trimV"], funcs["trimPrefix"], funcs["trimSuffix"],
funcs["replace"]) intentionally reverse the argument order compared to Sprig
equivalents so future contributors don't "fix" them; update the comment above
these overrides to mention the specific functions and their reversed signatures
(trimPrefix(pfx, s), trimSuffix(suffix, s), replace(old, new, s)) for clarity.

144-188: Rosetta2 / WindowsArmEmulation / Replacements / FormatOverrides logic duplicated with aqua.go.

buildTemplateData in this file (lines 144-188) and buildAssetTemplateData in pkg/toolchain/registry/aqua/aqua.go (lines 641-691) contain nearly identical logic for:

  • Rosetta2 fallback
  • Windows ARM emulation fallback
  • Applying replacements
  • Per-OS format overrides

This creates a maintenance risk — changes to one must be mirrored in the other. Consider extracting this into a shared helper.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/installer/asset.go` around lines 144 - 188, buildTemplateData
duplicates the Rosetta2/WindowsArmEmulation/Replacements/FormatOverrides logic
found in buildAssetTemplateData; extract that logic into a shared helper (e.g.,
normalizePlatform or computeAssetPlatform) that accepts the tool config and
runtime.GOOS/GOARCH and returns normalized OS, Arch, and Format (and optionally
GOOS/GOARCH if needed), then replace the inline logic in both buildTemplateData
and buildAssetTemplateData to call this helper; reference the fields
tool.Rosetta2, tool.WindowsArmEmulation, tool.Replacements, tool.FormatOverrides
and the functions buildTemplateData and buildAssetTemplateData when locating the
duplicated code.
pkg/toolchain/registry/aqua/aqua.go (1)

640-691: Significant code duplication with pkg/toolchain/installer/asset.go.

buildAssetTemplateData, assetTemplateFuncs, executeAssetTemplate, renderTemplate, and stripFileExtension are near-duplicates of their counterparts in asset.go. This creates a maintenance burden — a fix in one must be applied to both. Consider consolidating into a shared package.

Also applies to: 695-714, 720-772

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/registry/aqua/aqua.go` around lines 640 - 691, The functions
buildAssetTemplateData, assetTemplateFuncs, executeAssetTemplate,
renderTemplate, and stripFileExtension are duplicated between
pkg/toolchain/registry/aqua/aqua.go and pkg/toolchain/installer/asset.go;
refactor by extracting these functions into a new shared package (e.g.,
pkg/toolchain/template or pkg/toolchain/assets) and update both aqua.go and
asset.go to import that package and call the shared functions (retain existing
signatures like buildAssetTemplateData(tool *registry.Tool, releaseVersion,
semVer string) and assetTemplateFuncs() so callers need minimal changes); ensure
behavior-preserving details (OS/Arch replacement logic, Rosetta2 and
WindowsArmEmulation handling, and template func map) are moved intact and write
tests if present to validate no behavior change.
pkg/toolchain/installer/override.go (1)

12-14: Doc comment still only mentions GOOS/GOARCH matching.

The comment on ApplyPlatformOverrides says "If an override matches the current GOOS/GOARCH" but the function now also supports Envs-based matching via matchesOverride. Consider updating.

✏️ Suggested doc update
-// ApplyPlatformOverrides applies platform-specific overrides to the tool configuration.
-// If an override matches the current GOOS/GOARCH, it updates the tool's Asset, Format,
-// Files, and Replacements fields accordingly. First matching override wins.
+// ApplyPlatformOverrides applies platform-specific overrides to the tool configuration.
+// If an override matches the current platform (via Envs list or GOOS/GOARCH fields),
+// it updates the tool's Asset, Format, Files, and Replacements fields accordingly.
+// First matching override wins.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/installer/override.go` around lines 12 - 14, The doc comment
for ApplyPlatformOverrides is out of date: update it to state that overrides are
matched using the matchesOverride helper which checks GOOS/GOARCH and optional
Envs criteria (environment variable constraints), and that the first matching
override wins and will update the tool's Asset, Format, Files, and Replacements
fields; reference the ApplyPlatformOverrides function and matchesOverride in the
comment to make the matching behavior and precedence explicit.
pkg/toolchain/registry/aqua/aqua_test.go (1)

388-429: Sprig function tests look good.

One note: the "sprig title function" and "sprig upper function" cases only assert Contains(url, "tool-"), which is quite loose — it would pass even if title/upper weren't applied. Consider asserting a more specific substring if you want to verify the function actually transformed the value.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/registry/aqua/aqua_test.go` around lines 388 - 429, The
title/upper test cases are too loose; update
TestAquaRegistry_BuildAssetURL_SprigFunctions to set deterministic OS/Arch on
the registry.Tool (e.g., tool.OS = "linux", tool.Arch = "amd64") and replace the
generic assert.Contains checks with exact expected substrings for the
transformed results (for the "sprig title function" expect
"tool-Linux-amd64.tar.gz", for "sprig upper function" expect
"tool-LINUX-amd64.tar.gz"); keep the lower-case test as-is using RepoName "TOOL"
and SemVer "1.0.0" which should assert "tool-tool-1.0.0.tar.gz". Ensure you call
ar.BuildAssetURL(tool, "1.0.0") and assert the more specific substrings so the
tests actually verify the sprig transformations.
🤖 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/toolchain/registry/aqua/aqua.go`:
- Around line 258-264: The Rosetta2/WindowsArmEmulation flags are treated
additive-only because the code reads override.Rosetta2 and
override.WindowsArmEmulation as plain bools; change the override struct fields
to *bool (e.g., Override.Rosetta2 *bool, Override.WindowsArmEmulation *bool) and
update the application logic in the aqua merge code to check for nil vs
true/false (if override.Rosetta2 != nil { tool.Rosetta2 = *override.Rosetta2 }
and similarly for WindowsArmEmulation) so explicit false in an override will
disable the flag while nil leaves the existing tool value unchanged.

In `@pkg/toolchain/registry/aqua/version.go`:
- Around line 48-80: getLatestTag uses the package-level versionPrefix constant
("v") so custom tool prefixes are ignored; change getLatestTag signature on
AquaRegistry to accept a prefix string (e.g., getLatestTag(owner, repo, prefix
string)) and use that prefix in strings.TrimPrefix instead of the package
variable, then update the caller in GetLatestVersion to pass the tool's
VersionPrefix (tool.VersionPrefix) when invoking getLatestTag; ensure nil/error
flows remain unchanged and remove reliance on the package-level versionPrefix
for github_tag tools.

---

Duplicate comments:
In `@pkg/toolchain/registry/aqua/aqua_test.go`:
- Around line 1373-1378: The comment header "// Real-world registry YAML tests"
in aqua_test.go is missing a trailing period and fails the godot linter; update
that comment (the header line containing the text "Real-world registry YAML
tests") to end with a period ("// Real-world registry YAML tests.") so the
linter is satisfied.

In `@pkg/toolchain/registry/aqua/aqua.go`:
- Around line 190-211: The registry.ChecksumConfig struct is missing fields
parsed from YAML (checksum.asset, checksum.cosign.bundle, checksum.cosign.opts),
so update the struct definition used by versionOverride
(registry.ChecksumConfig) to include Asset string `yaml:"asset"`, CosignBundle
string `yaml:"cosign.bundle"` (or nested Cosign struct with Bundle and Opts and
appropriate yaml tags) and CosignOpts []string `yaml:"cosign.opts"` so those
values are not dropped during Unmarshal; keep the existing Type/URL/Algorithm
fields and ensure yaml tags match the YAML keys, then run/adjust any tests that
assert checksum parsing to verify the new fields are populated.

---

Nitpick comments:
In `@pkg/toolchain/installer/asset.go`:
- Around line 193-212: Add a short inline note inside assetTemplateFuncs()
explaining that the Aqua-specific wrapper functions (funcs["trimV"],
funcs["trimPrefix"], funcs["trimSuffix"], funcs["replace"]) intentionally
reverse the argument order compared to Sprig equivalents so future contributors
don't "fix" them; update the comment above these overrides to mention the
specific functions and their reversed signatures (trimPrefix(pfx, s),
trimSuffix(suffix, s), replace(old, new, s)) for clarity.
- Around line 144-188: buildTemplateData duplicates the
Rosetta2/WindowsArmEmulation/Replacements/FormatOverrides logic found in
buildAssetTemplateData; extract that logic into a shared helper (e.g.,
normalizePlatform or computeAssetPlatform) that accepts the tool config and
runtime.GOOS/GOARCH and returns normalized OS, Arch, and Format (and optionally
GOOS/GOARCH if needed), then replace the inline logic in both buildTemplateData
and buildAssetTemplateData to call this helper; reference the fields
tool.Rosetta2, tool.WindowsArmEmulation, tool.Replacements, tool.FormatOverrides
and the functions buildTemplateData and buildAssetTemplateData when locating the
duplicated code.

In `@pkg/toolchain/installer/override.go`:
- Around line 12-14: The doc comment for ApplyPlatformOverrides is out of date:
update it to state that overrides are matched using the matchesOverride helper
which checks GOOS/GOARCH and optional Envs criteria (environment variable
constraints), and that the first matching override wins and will update the
tool's Asset, Format, Files, and Replacements fields; reference the
ApplyPlatformOverrides function and matchesOverride in the comment to make the
matching behavior and precedence explicit.

In `@pkg/toolchain/registry/aqua/aqua_test.go`:
- Around line 388-429: The title/upper test cases are too loose; update
TestAquaRegistry_BuildAssetURL_SprigFunctions to set deterministic OS/Arch on
the registry.Tool (e.g., tool.OS = "linux", tool.Arch = "amd64") and replace the
generic assert.Contains checks with exact expected substrings for the
transformed results (for the "sprig title function" expect
"tool-Linux-amd64.tar.gz", for "sprig upper function" expect
"tool-LINUX-amd64.tar.gz"); keep the lower-case test as-is using RepoName "TOOL"
and SemVer "1.0.0" which should assert "tool-tool-1.0.0.tar.gz". Ensure you call
ar.BuildAssetURL(tool, "1.0.0") and assert the more specific substrings so the
tests actually verify the sprig transformations.

In `@pkg/toolchain/registry/aqua/aqua.go`:
- Around line 640-691: The functions buildAssetTemplateData, assetTemplateFuncs,
executeAssetTemplate, renderTemplate, and stripFileExtension are duplicated
between pkg/toolchain/registry/aqua/aqua.go and
pkg/toolchain/installer/asset.go; refactor by extracting these functions into a
new shared package (e.g., pkg/toolchain/template or pkg/toolchain/assets) and
update both aqua.go and asset.go to import that package and call the shared
functions (retain existing signatures like buildAssetTemplateData(tool
*registry.Tool, releaseVersion, semVer string) and assetTemplateFuncs() so
callers need minimal changes); ensure behavior-preserving details (OS/Arch
replacement logic, Rosetta2 and WindowsArmEmulation handling, and template func
map) are moved intact and write tests if present to validate no behavior change.

In `@pkg/toolchain/registry/url.go`:
- Around line 460-502: The two semver helpers (compareSemver and
evaluateSemverOp) are duplicated; extract them into a single shared
implementation in the parent registry package and have callers reuse it: move
the logic into a new registry-level function (e.g., registry.CompareSemver) that
incorporates the superset behavior from aqua/version.go (including the
isCommitHash guard/evaluateOp semantics), replace local calls to compareSemver
and evaluateSemverOp in url.go with the shared registry function, and remove the
duplicate functions to avoid divergence.
- Around line 442-455: The compile/run block using expr.Compile(constraint,
expr.Env(env)) should include expr.AsBool() to enforce boolean return at compile
time (mirroring aqua/version.go); update the expr.Compile call to
expr.Compile(constraint, expr.Env(env), expr.AsBool()) so expr.Run(program, env)
will always produce a bool, and then remove or optionally keep the manual type
assertion of output to bool (the explicit result, ok check in the current code
becomes redundant). Ensure you reference the same variables: constraint, env,
program, output/result and adjust error handling accordingly.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 3bf30fc and 14bf1eb.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (14)
  • NOTICE
  • go.mod
  • pkg/toolchain/installer/asset.go
  • pkg/toolchain/installer/asset_test.go
  • pkg/toolchain/installer/override.go
  • pkg/toolchain/installer/override_test.go
  • pkg/toolchain/installer/platform.go
  • pkg/toolchain/installer/platform_test.go
  • pkg/toolchain/registry/aqua/aqua.go
  • pkg/toolchain/registry/aqua/aqua_test.go
  • pkg/toolchain/registry/aqua/version.go
  • pkg/toolchain/registry/aqua/version_constraint_test.go
  • pkg/toolchain/registry/registry.go
  • pkg/toolchain/registry/url.go

Comment thread pkg/toolchain/registry/aqua/aqua.go Resolved
Comment thread pkg/toolchain/registry/aqua/version.go Resolved
… YAML output

expandFileSrcTemplate now resolves {{.Asset}} and {{.AssetWithoutExt}} by
first rendering the tool's asset template, matching the pattern used in
executeAssetTemplate. This fixes gum installation failing with "file not
found in archive: /gum" because AssetWithoutExt was empty.

Also adds omitempty tags to new Override fields (Envs, Type, URL) so empty
values don't appear in YAML output, fixing the golden snapshot mismatch.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (4)
pkg/toolchain/registry/aqua/aqua_test.go (1)

391-410: Strengthen Sprig-function assertions to validate transformed output.

At Line 397 through Line 405 and Line 424 through Line 427, checking only "tool-" doesn’t prove title/upper actually transformed values. The test currently proves rendering succeeds, but not behavior correctness for those functions.

🧪 Suggested tightening
-	tests := []struct {
-		name     string
-		asset    string
-		contains string
-	}{
+	tests := []struct {
+		name           string
+		asset          string
+		expectedSuffix string
+	}{
 		{
 			name:     "sprig title function",
-			asset:    "tool-{{title .OS}}-{{.Arch}}.tar.gz",
-			contains: "tool-",
+			asset:          "tool-{{title .RepoName}}-{{.SemVer}}.tar.gz",
+			expectedSuffix: "tool-Tool-1.0.0.tar.gz",
 		},
 		{
 			name:     "sprig upper function",
-			asset:    "tool-{{upper .OS}}-{{.Arch}}.tar.gz",
-			contains: "tool-",
+			asset:          "tool-{{upper .RepoName}}-{{.SemVer}}.tar.gz",
+			expectedSuffix: "tool-TOOL-1.0.0.tar.gz",
 		},
 		{
 			name:     "sprig lower function",
-			asset:    "tool-{{lower .RepoName}}-{{.SemVer}}.tar.gz",
-			contains: "tool-tool-1.0.0.tar.gz",
+			asset:          "tool-{{lower .RepoName}}-{{.SemVer}}.tar.gz",
+			expectedSuffix: "tool-tool-1.0.0.tar.gz",
 		},
 	}
@@
-			assert.Contains(t, url, tt.contains)
+			assert.Contains(t, url, tt.expectedSuffix)

As per coding guidelines, "Every new feature must include comprehensive unit tests targeting >80% code coverage for all packages."

Also applies to: 424-427

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/registry/aqua/aqua_test.go` around lines 391 - 410, The tests
for the sprig transformations only assert the presence of "tool-" and don't
verify that title/upper/lower actually transformed the input; update the
table-driven tests in aqua_test.go (the cases named "sprig title function",
"sprig upper function", "sprig lower function" that use asset templates like
"tool-{{title .OS}}-{{.Arch}}.tar.gz", "tool-{{upper .OS}}-{{.Arch}}.tar.gz",
"tool-{{lower .RepoName}}-{{.SemVer}}.tar.gz") to assert the rendered output
equals or contains the correctly transformed string (e.g., for title ensure the
.OS value is title-cased in the result, for upper ensure .OS is uppercased, for
lower ensure .RepoName is lowercased and combined with .SemVer), by supplying
controlled input values for .OS/.RepoName/.SemVer and asserting the exact
expected asset filename instead of just "tool-".
pkg/toolchain/registry/aqua/aqua.go (3)

648-658: Heads-up: getOS() called twice per invocation.

getOS() is called at line 654 (inside the FormatOverrides loop) and again at line 661. Both should return the same value. Consider capturing it once at the top to avoid the redundant call and make the data flow clearer.

♻️ Minor cleanup
 func buildAssetTemplateData(tool *registry.Tool, releaseVersion, semVer string) map[string]string {
 	format := tool.Format
+
+	osVal := getOS()
+	archVal := getArch()
+
 	for _, fo := range tool.FormatOverrides {
-		if fo.GOOS == getOS() {
+		if fo.GOOS == osVal {
 			format = fo.Format
 			break
 		}
 	}
 
-	osVal := getOS()
-	archVal := getArch()
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/registry/aqua/aqua.go` around lines 648 - 658, The code calls
getOS() multiple times when deciding the format override; capture the OS once
(e.g., os := getOS()) before using tool.Format and tool.FormatOverrides, then
compare fo.GOOS to that captured variable and also use it wherever getOS() was
used later in this block so the value is computed once and the data flow is
clearer (update references around the logic using tool.Format,
tool.FormatOverrides, and the getOS() comparisons).

752-753: assetTemplateFuncs() is rebuilt on every renderTemplate call.

With two-pass rendering, this allocates the full Sprig function map twice per asset URL. For the current toolchain install workload (a handful of tools) this is negligible, but if this path ever gets hot, consider caching the FuncMap at package level via sync.Once.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/registry/aqua/aqua.go` around lines 752 - 753, The call site
renderTemplate currently invokes assetTemplateFuncs() on every call, rebuilding
the full Sprig FuncMap each time; change this by creating a package-level cached
variable (e.g., var assetFuncs template.FuncMap) and initialize it once using
sync.Once (e.g., var assetFuncsOnce sync.Once) inside the package, then have
renderTemplate use the cached assetFuncs instead of calling assetTemplateFuncs()
repeatedly so the heavy FuncMap is constructed only once.

739-746: Pass 2 guard relies on substring match, which is fragile.

strings.Contains(assetTemplate, ".Asset") will also match .Assets, .AssetID, or any other identifier starting with .Asset. A more precise check would be:

strings.Contains(assetTemplate, ".Asset}}") || strings.Contains(assetTemplate, ".Asset ") || strings.Contains(assetTemplate, ".AssetWithoutExt")

That said, false positives here only trigger a harmless extra render pass, so this is low-risk.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/registry/aqua/aqua.go` around lines 739 - 746, The current
guard uses strings.Contains(assetTemplate, ".Asset") which is too broad; update
the condition in the block around assetTemplate handling to detect only real
template tokens (e.g., check for ".Asset}}" or ".Asset " or references to
".AssetWithoutExt") before doing the extra render pass so you only perform the
second render when the template actually references those fields; keep the
existing logic that sets data["Asset"] and data["AssetWithoutExt"] and then
calls renderTemplate(result, data) and stripFileExtension as before.
🤖 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/toolchain/registry/aqua/version.go`:
- Around line 26-30: The code currently ignores errors from ar.GetTool and falls
back to releases, which can hide registry resolution failures; change the logic
in the version-source dispatch so that if ar.GetTool(owner, repo) returns a
non-nil err you return or propagate a wrapped error (e.g. using
fmt.Errorf("GetTool %s/%s: %w", owner, repo, err)) instead of silently
continuing, and only call ar.getLatestTag(owner, repo, tool.VersionPrefix) when
err == nil and tool.VersionSource == "github_tag"; ensure you use fmt.Errorf to
add context when returning the GetTool error.

---

Nitpick comments:
In `@pkg/toolchain/registry/aqua/aqua_test.go`:
- Around line 391-410: The tests for the sprig transformations only assert the
presence of "tool-" and don't verify that title/upper/lower actually transformed
the input; update the table-driven tests in aqua_test.go (the cases named "sprig
title function", "sprig upper function", "sprig lower function" that use asset
templates like "tool-{{title .OS}}-{{.Arch}}.tar.gz", "tool-{{upper
.OS}}-{{.Arch}}.tar.gz", "tool-{{lower .RepoName}}-{{.SemVer}}.tar.gz") to
assert the rendered output equals or contains the correctly transformed string
(e.g., for title ensure the .OS value is title-cased in the result, for upper
ensure .OS is uppercased, for lower ensure .RepoName is lowercased and combined
with .SemVer), by supplying controlled input values for .OS/.RepoName/.SemVer
and asserting the exact expected asset filename instead of just "tool-".

In `@pkg/toolchain/registry/aqua/aqua.go`:
- Around line 648-658: The code calls getOS() multiple times when deciding the
format override; capture the OS once (e.g., os := getOS()) before using
tool.Format and tool.FormatOverrides, then compare fo.GOOS to that captured
variable and also use it wherever getOS() was used later in this block so the
value is computed once and the data flow is clearer (update references around
the logic using tool.Format, tool.FormatOverrides, and the getOS() comparisons).
- Around line 752-753: The call site renderTemplate currently invokes
assetTemplateFuncs() on every call, rebuilding the full Sprig FuncMap each time;
change this by creating a package-level cached variable (e.g., var assetFuncs
template.FuncMap) and initialize it once using sync.Once (e.g., var
assetFuncsOnce sync.Once) inside the package, then have renderTemplate use the
cached assetFuncs instead of calling assetTemplateFuncs() repeatedly so the
heavy FuncMap is constructed only once.
- Around line 739-746: The current guard uses strings.Contains(assetTemplate,
".Asset") which is too broad; update the condition in the block around
assetTemplate handling to detect only real template tokens (e.g., check for
".Asset}}" or ".Asset " or references to ".AssetWithoutExt") before doing the
extra render pass so you only perform the second render when the template
actually references those fields; keep the existing logic that sets
data["Asset"] and data["AssetWithoutExt"] and then calls renderTemplate(result,
data) and stripFileExtension as before.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 14bf1eb and d324da9.

📒 Files selected for processing (7)
  • pkg/toolchain/installer/asset_test.go
  • pkg/toolchain/installer/extract.go
  • pkg/toolchain/installer/extract_test.go
  • pkg/toolchain/registry/aqua/aqua.go
  • pkg/toolchain/registry/aqua/aqua_test.go
  • pkg/toolchain/registry/aqua/version.go
  • pkg/toolchain/registry/registry.go

Comment thread pkg/toolchain/registry/aqua/version.go Resolved
@codecov

codecov Bot commented Feb 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 83.25581% with 72 lines in your changes missing coverage. Please review.
✅ Project coverage is 76.49%. Comparing base (ee6a167) to head (03976dd).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
pkg/toolchain/registry/aqua/aqua.go 84.96% 12 Missing and 11 partials ⚠️
pkg/github/releases.go 0.00% 15 Missing ⚠️
pkg/toolchain/registry/aqua/version.go 84.93% 6 Missing and 5 partials ⚠️
pkg/toolchain/registry/url.go 86.27% 3 Missing and 4 partials ⚠️
pkg/toolchain/installer/asset.go 86.04% 3 Missing and 3 partials ⚠️
pkg/version/reexec.go 79.31% 6 Missing ⚠️
pkg/toolchain/installer/extract.go 66.66% 1 Missing and 1 partial ⚠️
pkg/toolchain/installer/installer.go 75.00% 1 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #2107      +/-   ##
==========================================
+ Coverage   76.31%   76.49%   +0.18%     
==========================================
  Files         831      831              
  Lines       78809    79059     +250     
==========================================
+ Hits        60146    60480     +334     
+ Misses      14901    14810      -91     
- Partials     3762     3769       +7     
Flag Coverage Δ
unittests 76.49% <83.25%> (+0.18%) ⬆️

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

Files with missing lines Coverage Δ
pkg/github/client.go 95.60% <100.00%> (+0.54%) ⬆️
pkg/toolchain/installer/download.go 89.47% <100.00%> (+4.85%) ⬆️
pkg/toolchain/installer/override.go 100.00% <100.00%> (ø)
pkg/toolchain/installer/platform.go 100.00% <100.00%> (ø)
pkg/toolchain/installer/version.go 85.52% <100.00%> (ø)
pkg/toolchain/registry/registry.go 57.14% <ø> (ø)
pkg/toolchain/installer/extract.go 67.46% <66.66%> (-0.02%) ⬇️
pkg/toolchain/installer/installer.go 77.38% <75.00%> (+0.70%) ⬆️
pkg/toolchain/installer/asset.go 92.64% <86.04%> (-3.94%) ⬇️
pkg/version/reexec.go 94.00% <79.31%> (+11.67%) ⬆️
... and 4 more

... and 4 files with indirect coverage changes

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

errUtils.Format() already renders markdown through Glamour producing
final ANSI-styled output. Passing that output to ui.Errorf() re-rendered
it through Glamour a second time, causing nested/garbled ANSI escape
sequences that showed as raw text on WSL2 and other terminals.

Write pre-rendered error output directly to stderr via ioLayer.MaskWriter(),
matching the correct pattern used in main.go.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
… errors

Move "Consider setting ATMOS_GITHUB_TOKEN" text from the error message
into proper WithHint() calls so it renders in the Hints section instead
of the Error line.

Hints are now context-aware: if a token IS set, hints suggest verifying
it; if no token is set, hints suggest setting one.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ckages

Add and fix tests across 6 test files (+1,237 lines) to improve patch
coverage toward the 80% target. Key changes:

- Fix TestGetLatestVersion_GitHubTag by pre-populating disk cache
- Fix two-pass rendering tests to actually trigger the .Asset code path
- Add composite registry tests for Search, ListAll, GetMetadata
- Add installer tests for WithAtmosConfig, ListInstalledVersions, etc.
- Fix download_test.go missing imports and broken TestTryFallbackVersion

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🧹 Nitpick comments (8)
pkg/toolchain/installer/installer_test.go (2)

1165-1191: Replace hand-written mock with mockgen-generated one.

mockRegistryForInstaller is a manual stub. Per coding guidelines, all mocks must be generated via go.uber.org/mock/mockgen with a //go:generate directive — never written by hand. A generated mock also gives you call-count assertions via EXPECT() for free if needed later.

♻️ Suggested replacement

Add a generate directive in the package (or a dedicated mock_test.go):

+//go:generate go run go.uber.org/mock/mockgen -destination mock_registry_test.go -package installer github.com/cloudposse/atmos/pkg/toolchain/registry ToolRegistry

Then in TestWithConfiguredRegistry, swap in the generated mock:

-	mockReg := &mockRegistryForInstaller{}
+	ctrl := gomock.NewController(t)
+	defer ctrl.Finish()
+	mockReg := NewMockToolRegistry(ctrl)

And delete the mockRegistryForInstaller struct and all its method implementations (lines 1166–1191).

As per coding guidelines: "Use go.uber.org/mock/mockgen with //go:generate directives. Never manual mocks."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/installer/installer_test.go` around lines 1165 - 1191, The test
contains a handwritten stub type mockRegistryForInstaller with its methods —
replace it with a mockgen-generated mock: add a //go:generate directive in the
package (e.g., targeting interface registry.ToolRegistry) to produce a mock
(e.g., mock_registry.go), run mockgen to generate the mock, update
TestWithConfiguredRegistry to instantiate and use the generated mock's
constructor/EXPECT plumbing instead of mockRegistryForInstaller, and remove the
mockRegistryForInstaller type and its method implementations from the file.

1151-1163: Weak assertion — consider pinning known paths.

The test only verifies that the tool name appears in some path. If buildCommonRegistryPaths returns an incorrect set of paths, this won't catch it.

♻️ Suggested improvement
 func TestBuildCommonRegistryPaths(t *testing.T) {
 	paths := buildCommonRegistryPaths("terraform")
 	assert.NotEmpty(t, paths)
-	// Should contain a path with the tool name.
-	found := false
-	for _, p := range paths {
-		if strings.Contains(p, "terraform") {
-			found = true
-			break
-		}
-	}
-	assert.True(t, found, "paths should contain the tool name")
+	// Every returned path should reference the tool name.
+	for _, p := range paths {
+		assert.Contains(t, p, "terraform", "path %q should contain the tool name", p)
+	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/installer/installer_test.go` around lines 1151 - 1163,
TestBuildCommonRegistryPaths uses a weak assertion; replace the loose substring
check with a deterministic assertion against expected paths from
buildCommonRegistryPaths("terraform"). Update the test to define the exact
expected slice of registry paths (or a set) and assert
equality/order-insensitive equality (e.g., compare lengths and membership or use
assert.ElementsMatch) with the result of buildCommonRegistryPaths; reference the
TestBuildCommonRegistryPaths test and buildCommonRegistryPaths function when
making the change.
pkg/toolchain/registry/aqua/aqua_test.go (2)

2663-2706: Duplicate test coverage — TestExtractBinaryNameFromPackageName_AllCases and TestStripFileExtension_Aqua repeat cases already covered above.

  • TestExtractBinaryNameFromPackageName_AllCases (lines 2663–2683) covers the same function and effectively the same cases as TestExtractBinaryNameFromPackageName (lines 2059–2098).
  • TestStripFileExtension_Aqua (lines 2685–2706) duplicates TestStripFileExtension (lines 2262–2286).

Consolidate into the existing table-driven tests rather than maintaining parallel duplicates.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/registry/aqua/aqua_test.go` around lines 2663 - 2706, Remove
the duplicate test functions TestExtractBinaryNameFromPackageName_AllCases and
TestStripFileExtension_Aqua and consolidate any unique cases into the existing
table-driven tests TestExtractBinaryNameFromPackageName and
TestStripFileExtension; specifically, ensure all cases for the
extractBinaryNameFromPackageName and stripFileExtension functions are present in
the original tests' tables (add any missing inputs/expected rows) and then
delete the duplicate test definitions to avoid redundant coverage.

388-429: Weak assertions in title and upper sub-cases don't verify the Sprig function behavior.

Both the "sprig title function" and "sprig upper function" cases only assert Contains(t, url, "tool-"), which would pass even if the functions silently no-op. The lower case is the only one that verifies the actual transformed output. Consider adding precise expected values like the lower case does.

✏️ Proposed fix
 		{
 			name:     "sprig title function",
 			asset:    "tool-{{title .OS}}-{{.Arch}}.tar.gz",
-			contains: "tool-",
+			contains: "tool-Darwin-",
 		},
 		{
 			name:     "sprig upper function",
 			asset:    "tool-{{upper .OS}}-{{.Arch}}.tar.gz",
-			contains: "tool-",
+			contains: "tool-LINUX-",
 		},

Note: These are heuristic — wrap in a runtime check or accept the platform dependency (test runs on linux).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/registry/aqua/aqua_test.go` around lines 388 - 429, Update
TestAquaRegistry_BuildAssetURL_SprigFunctions to assert exact transformed
outputs instead of the weak "tool-" check: compute the expected values from
runtime (e.g., expectedTitle := strings.Title(runtime.GOOS) and expectedUpper :=
strings.ToUpper(runtime.GOOS) or build them using runtime.GOOS/runtime.GOARCH)
and replace the contains entries for the "sprig title function" and "sprig upper
function" cases with those exact expected substrings (used against
ar.BuildAssetURL(tool, "1.0.0") for each registry.Tool test case) so the test
verifies the actual Sprig transformations.
pkg/toolchain/installer/asset_test.go (1)

816-885: Two-pass rendering tests look solid — one minor observation on the self-referential asset value.

In the "template referencing .Asset directly triggers second pass" sub-test (lines 846–865), the pass-1 result used as data.Asset in pass 2 will include the trailing / (e.g., "tool_1.0.0_linux_amd64.tar.gz/"), so AssetWithoutExt will strip the trailing slash rather than a file extension. The assertion on line 864 is loose enough (Contains) to stay green, but if the production rendering logic changes how Asset is set it could silently mask regressions. A tighter assertion — e.g., verifying the exact data.Asset value — would be more valuable here.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/installer/asset_test.go` around lines 816 - 885, The test
"template referencing .Asset directly triggers second pass" uses a loose
assertion (assert.Contains) and doesn't verify the exact self-referential value
set on data.Asset after pass 1; change the sub-test to assert the exact expected
pass-1 value (including the trailing "/") on data.Asset and then verify
AssetWithoutExt is computed correctly (e.g., assert.Equal(t,
"tool_1.0.0_linux_amd64.tar.gz/", data.Asset) and assert.Equal(t,
"tool_1.0.0_linux_amd64", data.AssetWithoutExt)) so executeAssetTemplate,
data.Asset and AssetWithoutExt behavior is explicitly validated rather than
relying on Contains.
pkg/toolchain/registry/composite_test.go (1)

301-473: Consider converting the repeated scenario tests to table-driven form.

Search/ListAll/GetMetadata success+error variants are a strong fit for table cases; this will cut duplication and make new edge cases cheaper to add.

As per coding guidelines, Use table-driven tests for testing multiple scenarios in Go.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/registry/composite_test.go` around lines 301 - 473, Several
tests (TestCompositeRegistry_Search,
TestCompositeRegistry_Search_ErrorContinues, TestCompositeRegistry_ListAll,
TestCompositeRegistry_ListAll_ErrorContinues, TestCompositeRegistry_GetMetadata,
TestCompositeRegistry_GetMetadata_ErrorContinues) duplicate the same pattern and
should be converted to a table-driven style: create a slice of test cases with
fields like name, registries (slice of PrioritizedRegistry), query (for Search),
expectedCount, and expectedErrorFlag; then loop over cases and call
t.Run(case.name, func(t *testing.T) { ... }) and inside invoke
NewCompositeRegistry(...) and call composite.Search / composite.ListAll /
composite.GetMetadata as appropriate, asserting expected counts/errors. Use the
searchableMockRegistry instances as case setup
(searchResults/searchErr/listResults/listErr/metadataErr) and keep existing
behavior of deduplication/priorities; ensure each case initializes its
registries rather than sharing mutable state.
pkg/github/releases.go (1)

80-97: Extract the token-based hint block into one shared helper.

This conditional hint composition is now duplicated here and in pkg/github/client.go, which can drift over time.

Suggested refactor.
-			if httpClient.GetGitHubTokenFromEnv() != "" {
-				builder.
-					WithHint("Your GitHub token may be invalid or expired").
-					WithHint("Verify your token: `gh auth status` or check `ATMOS_GITHUB_TOKEN` / `GITHUB_TOKEN`")
-			} else {
-				builder.
-					WithHint("Set `ATMOS_GITHUB_TOKEN` or `GITHUB_TOKEN` environment variable for higher rate limits").
-					WithHint("Generate a token at: https://github.com/settings/tokens")
-			}
+			addGitHubTokenHints(builder)
// addGitHubTokenHints appends troubleshooting hints based on token presence.
func addGitHubTokenHints(builder *errUtils.ErrorBuilder) {
	if httpClient.GetGitHubTokenFromEnv() != "" {
		builder.
			WithHint("Your GitHub token may be invalid or expired").
			WithHint("Verify your token: `gh auth status` or check `ATMOS_GITHUB_TOKEN` / `GITHUB_TOKEN`")
		return
	}

	builder.
		WithHint("Set `ATMOS_GITHUB_TOKEN` or `GITHUB_TOKEN` environment variable for higher rate limits").
		WithHint("Generate a token at: https://github.com/settings/tokens")
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/github/releases.go` around lines 80 - 97, Extract the duplicated
token-based hint composition into a single helper (e.g., addGitHubTokenHints)
that takes an *errUtils.ErrorBuilder and appends the two hint branches by
checking httpClient.GetGitHubTokenFromEnv(); replace the inline conditional in
the function that constructs the ErrGitHubRateLimitExceeded builder (and the
similar block in the code that previously duplicated this logic) to call
addGitHubTokenHints(builder) instead. Ensure the helper signature references
*errUtils.ErrorBuilder, uses the same hint strings, and leaves the existing
builder.Err() return behavior unchanged so callers (like the rate-limit handling
code using builder) continue to return nil, builder.Err().
pkg/toolchain/registry/url_test.go (1)

461-474: Consider using named fields in table test entries.

Positional struct literals become fragile if fields are ever reordered and harder to scan for reviewers. Named fields are the idiomatic Go style for table-driven tests.

♻️ Example refactor (first few entries)
-		{"empty constraint", "", "1.0.0", false, false},
-		{"literal true", "true", "1.0.0", true, false},
+		{name: "empty constraint", constraint: "", version: "1.0.0", want: false, wantErr: false},
+		{name: "literal true", constraint: "true", version: "1.0.0", want: true, wantErr: false},
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/registry/url_test.go` around lines 461 - 474, Convert the
positional struct literals in the table-driven test (the slice containing
entries like "empty constraint", "literal true", etc.) to use named fields
(e.g., Name:, Constraint:, Version:, Want:, WantErr:) so each entry is
explicitly labeled; update every entry in that test table to use those field
names and ensure the boolean and string values match the original semantics.
Ensure you use the actual struct field names from the test's case type (match
capitalization exactly) and apply the change to all rows in that slice so
reordering fields later won't break the tests.
🤖 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/github/client.go`:
- Around line 95-110: The rate-limit branch currently drops the original error
`err`; update the builder created by
`errUtils.Build(errUtils.ErrGitHubRateLimitExceeded)` to attach the original
`err` as the cause before returning (e.g., call the builder's method to record
the underlying error such as `WithCause(err)` or the project-equivalent) so
upstream debugging retains the original GitHub API error; keep the existing
token-check hints (`httpClient.GetGitHubTokenFromEnv()`, `WithHint(...)`) and
then return `builder.Err()`.

In `@pkg/toolchain/installer/download_test.go`:
- Line 275: Update the inline comments in
pkg/toolchain/installer/download_test.go so they end with trailing periods to
satisfy the godot linter: modify the comment on the line with "prefix :=
VersionPrefix" and the other inline comments nearby (the ones referenced at
lines 287, 302, and 315) to include a period at the end. Ensure each inline
comment string for these occurrences is updated to end with a '.' without
changing the surrounding code or semantics.
- Around line 491-537: The tests in TestTryFallbackVersion only assert an error
and don't verify the actual requested paths, so add request capturing to each
httptest server handler (e.g., record r.URL.Path into a slice or channel with
synchronization) and assert that tryFallbackVersion (called on Installer with
registry.Tool) first requests the original asset path then the expected fallback
path: for input "1.0.0" expect "/tool-1.0.0.tar.gz" then "/tool-v1.0.0.tar.gz",
and for input "v1.0.0" expect "/tool-v1.0.0.tar.gz" then "/tool-1.0.0.tar.gz";
keep the existing assert.Error checks and ensure the recorder is thread-safe
(Mutex or channel) so the test deterministically validates the prefix-toggle
logic.

In `@pkg/toolchain/registry/composite_test.go`:
- Around line 301-413: Update the tests to assert concrete result identities
instead of only lengths: in TestCompositeRegistry_Search verify that the
returned results include hashicorp/terraform (Name "terraform" from reg1) and
hashicorp/packer (from reg2) and that hashicorp/terraform is the one from the
high-priority registry (reg1) rather than the duplicate "terraform-dup" from
reg2; in TestCompositeRegistry_Search_ErrorContinues assert the single result is
terraform with RepoOwner "hashicorp" and RepoName "terraform" (from reg2); in
TestCompositeRegistry_ListAll_ErrorContinues assert the returned tool has
RepoOwner "owner" and RepoName "repo" (from reg2). Use the existing
variables/results slice and the test names (TestCompositeRegistry_Search,
TestCompositeRegistry_Search_ErrorContinues,
TestCompositeRegistry_ListAll_ErrorContinues) and registry mocks (reg1/reg2,
searchableMockRegistry) to locate the assertions to change.

In `@pkg/toolchain/registry/url_test.go`:
- Around line 354-370: The test "version matching override" currently only
checks toolWithVersion.Version and leaves a dangling "_ = tool"; update the test
(around reg.GetTool and reg.GetToolWithVersion usage) to assert the override
applied other fields from the fixture: verify toolWithVersion.Asset matches the
legacy asset pattern (e.g., startsWith "tool-legacy-" or equals the expected
asset for version "0.9.0") and that toolWithVersion.Format == "zip"; remove the
unused "_ = tool" and keep the existing Version assertion so the test validates
version, asset and format overrides together.

In `@pkg/version/reexec.go`:
- Around line 188-205: The three direct stderr writes in reexec.go (using
ioLayer.MaskWriter(os.Stderr).Write) should be replaced with a ui-layer call:
add a new ui helper (e.g., ui.WriteErrRaw(string)) that accepts an
already-formatted string and writes it through the UI's masked writer, then
update the calls in the branches that handle
toolchain.IsSHAVersion(requestedVersion) and the invalid parse
(toolchain.ParseVersionSpec) as well as the earlier error branch to call
ui.WriteErrRaw(formatted); also extract the repeated pattern of formatting the
error and exiting into a small private helper in this file (e.g.,
writeErrAndExit(formatted string)) that calls ui.WriteErrRaw and os.Exit(1), and
update all three sites to use that helper so the UI owns stderr output and the
code is deduplicated.

---

Nitpick comments:
In `@pkg/github/releases.go`:
- Around line 80-97: Extract the duplicated token-based hint composition into a
single helper (e.g., addGitHubTokenHints) that takes an *errUtils.ErrorBuilder
and appends the two hint branches by checking
httpClient.GetGitHubTokenFromEnv(); replace the inline conditional in the
function that constructs the ErrGitHubRateLimitExceeded builder (and the similar
block in the code that previously duplicated this logic) to call
addGitHubTokenHints(builder) instead. Ensure the helper signature references
*errUtils.ErrorBuilder, uses the same hint strings, and leaves the existing
builder.Err() return behavior unchanged so callers (like the rate-limit handling
code using builder) continue to return nil, builder.Err().

In `@pkg/toolchain/installer/asset_test.go`:
- Around line 816-885: The test "template referencing .Asset directly triggers
second pass" uses a loose assertion (assert.Contains) and doesn't verify the
exact self-referential value set on data.Asset after pass 1; change the sub-test
to assert the exact expected pass-1 value (including the trailing "/") on
data.Asset and then verify AssetWithoutExt is computed correctly (e.g.,
assert.Equal(t, "tool_1.0.0_linux_amd64.tar.gz/", data.Asset) and
assert.Equal(t, "tool_1.0.0_linux_amd64", data.AssetWithoutExt)) so
executeAssetTemplate, data.Asset and AssetWithoutExt behavior is explicitly
validated rather than relying on Contains.

In `@pkg/toolchain/installer/installer_test.go`:
- Around line 1165-1191: The test contains a handwritten stub type
mockRegistryForInstaller with its methods — replace it with a mockgen-generated
mock: add a //go:generate directive in the package (e.g., targeting interface
registry.ToolRegistry) to produce a mock (e.g., mock_registry.go), run mockgen
to generate the mock, update TestWithConfiguredRegistry to instantiate and use
the generated mock's constructor/EXPECT plumbing instead of
mockRegistryForInstaller, and remove the mockRegistryForInstaller type and its
method implementations from the file.
- Around line 1151-1163: TestBuildCommonRegistryPaths uses a weak assertion;
replace the loose substring check with a deterministic assertion against
expected paths from buildCommonRegistryPaths("terraform"). Update the test to
define the exact expected slice of registry paths (or a set) and assert
equality/order-insensitive equality (e.g., compare lengths and membership or use
assert.ElementsMatch) with the result of buildCommonRegistryPaths; reference the
TestBuildCommonRegistryPaths test and buildCommonRegistryPaths function when
making the change.

In `@pkg/toolchain/registry/aqua/aqua_test.go`:
- Around line 2663-2706: Remove the duplicate test functions
TestExtractBinaryNameFromPackageName_AllCases and TestStripFileExtension_Aqua
and consolidate any unique cases into the existing table-driven tests
TestExtractBinaryNameFromPackageName and TestStripFileExtension; specifically,
ensure all cases for the extractBinaryNameFromPackageName and stripFileExtension
functions are present in the original tests' tables (add any missing
inputs/expected rows) and then delete the duplicate test definitions to avoid
redundant coverage.
- Around line 388-429: Update TestAquaRegistry_BuildAssetURL_SprigFunctions to
assert exact transformed outputs instead of the weak "tool-" check: compute the
expected values from runtime (e.g., expectedTitle := strings.Title(runtime.GOOS)
and expectedUpper := strings.ToUpper(runtime.GOOS) or build them using
runtime.GOOS/runtime.GOARCH) and replace the contains entries for the "sprig
title function" and "sprig upper function" cases with those exact expected
substrings (used against ar.BuildAssetURL(tool, "1.0.0") for each registry.Tool
test case) so the test verifies the actual Sprig transformations.

In `@pkg/toolchain/registry/composite_test.go`:
- Around line 301-473: Several tests (TestCompositeRegistry_Search,
TestCompositeRegistry_Search_ErrorContinues, TestCompositeRegistry_ListAll,
TestCompositeRegistry_ListAll_ErrorContinues, TestCompositeRegistry_GetMetadata,
TestCompositeRegistry_GetMetadata_ErrorContinues) duplicate the same pattern and
should be converted to a table-driven style: create a slice of test cases with
fields like name, registries (slice of PrioritizedRegistry), query (for Search),
expectedCount, and expectedErrorFlag; then loop over cases and call
t.Run(case.name, func(t *testing.T) { ... }) and inside invoke
NewCompositeRegistry(...) and call composite.Search / composite.ListAll /
composite.GetMetadata as appropriate, asserting expected counts/errors. Use the
searchableMockRegistry instances as case setup
(searchResults/searchErr/listResults/listErr/metadataErr) and keep existing
behavior of deduplication/priorities; ensure each case initializes its
registries rather than sharing mutable state.

In `@pkg/toolchain/registry/url_test.go`:
- Around line 461-474: Convert the positional struct literals in the
table-driven test (the slice containing entries like "empty constraint",
"literal true", etc.) to use named fields (e.g., Name:, Constraint:, Version:,
Want:, WantErr:) so each entry is explicitly labeled; update every entry in that
test table to use those field names and ensure the boolean and string values
match the original semantics. Ensure you use the actual struct field names from
the test's case type (match capitalization exactly) and apply the change to all
rows in that slice so reordering fields later won't break the tests.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between d324da9 and 309243e.

📒 Files selected for processing (9)
  • pkg/github/client.go
  • pkg/github/releases.go
  • pkg/toolchain/installer/asset_test.go
  • pkg/toolchain/installer/download_test.go
  • pkg/toolchain/installer/installer_test.go
  • pkg/toolchain/registry/aqua/aqua_test.go
  • pkg/toolchain/registry/composite_test.go
  • pkg/toolchain/registry/url_test.go
  • pkg/version/reexec.go

Comment thread pkg/github/client.go Resolved
Comment thread pkg/toolchain/registry/url_test.go Resolved
Comment thread pkg/version/reexec.go Resolved
…packages

Preserve original GitHub API error as cause in rate limit handler, fix godot
linter violations in test comments, strengthen test assertions to verify
fallback URL construction and registry precedence/dedup semantics, validate
version override fields, and route stderr output through UI layer in reexec.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
pkg/toolchain/registry/url_test.go (1)

412-420: Use filepath.Join() for the test path input.

The hardcoded "/nonexistent/path" is platform-specific.

♻️ Proposed fix
 import (
 	"context"
 	"net/http"
 	"net/http/httptest"
+	"path/filepath"
 	"strings"
 	"testing"
 )
@@
-	err := reg.LoadLocalConfig("/nonexistent/path")
+	err := reg.LoadLocalConfig(filepath.Join("nonexistent", "path"))

As per coding guidelines, "Use filepath.Join() for cross-platform path handling instead of hardcoded path separators... Never use forward slash concatenation in tests."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/registry/url_test.go` around lines 412 - 420, The test
TestURLRegistry_LoadLocalConfig uses a hardcoded path string "/nonexistent/path"
which is platform-specific; update the test to build the path using
filepath.Join (importing "path/filepath" in the test file if missing) and pass
filepath.Join("nonexistent", "path") (or an appropriate joined path) to
reg.LoadLocalConfig so the test runs correctly on Windows and Unix; ensure the
change references TestURLRegistry_LoadLocalConfig and the call to
reg.LoadLocalConfig.
pkg/toolchain/registry/composite_test.go (1)

245-256: Use filepath.Join() for the test config path.

The hardcoded "/some/path" is Unix-specific.

♻️ Proposed fix
 import (
 	"context"
 	"errors"
+	"path/filepath"
 	"testing"
 
 	"github.com/cloudposse/atmos/pkg/perf"
 )
@@
-	err := composite.LoadLocalConfig("/some/path")
+	err := composite.LoadLocalConfig(filepath.Join("some", "path"))

As per coding guidelines, "Use filepath.Join() for cross-platform path handling instead of hardcoded path separators... Never use forward slash concatenation in tests."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/registry/composite_test.go` around lines 245 - 256, Replace the
hardcoded Unix-specific path string in TestCompositeRegistry_LoadLocalConfig
where composite.LoadLocalConfig("/some/path") is called with a cross-platform
path created via filepath.Join (e.g., filepath.Join("some", "path")), and add
the necessary import for "path/filepath" at the top of the test file; keep the
call to composite.LoadLocalConfig and the test assertion unchanged.
🤖 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/toolchain/registry/url_test.go`:
- Around line 379-387: The test "version not matching override uses defaults"
currently only asserts Version; extend it to also assert that Asset and Format
revert to the default values rather than inheriting the override fields: after
calling reg.GetToolWithVersion("test", "tool", "2.0.0") and checking
toolWithVersion.Version, add assertions that toolWithVersion.Asset equals the
package's default asset value and toolWithVersion.Format equals the default
format (the defaults used elsewhere in the registry code), so the test will
catch any leakage of override.Asset/override.Format into non-matching versions.

---

Nitpick comments:
In `@pkg/toolchain/registry/composite_test.go`:
- Around line 245-256: Replace the hardcoded Unix-specific path string in
TestCompositeRegistry_LoadLocalConfig where
composite.LoadLocalConfig("/some/path") is called with a cross-platform path
created via filepath.Join (e.g., filepath.Join("some", "path")), and add the
necessary import for "path/filepath" at the top of the test file; keep the call
to composite.LoadLocalConfig and the test assertion unchanged.

In `@pkg/toolchain/registry/url_test.go`:
- Around line 412-420: The test TestURLRegistry_LoadLocalConfig uses a hardcoded
path string "/nonexistent/path" which is platform-specific; update the test to
build the path using filepath.Join (importing "path/filepath" in the test file
if missing) and pass filepath.Join("nonexistent", "path") (or an appropriate
joined path) to reg.LoadLocalConfig so the test runs correctly on Windows and
Unix; ensure the change references TestURLRegistry_LoadLocalConfig and the call
to reg.LoadLocalConfig.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 309243e and 7d0d932.

📒 Files selected for processing (5)
  • pkg/github/client.go
  • pkg/toolchain/installer/download_test.go
  • pkg/toolchain/registry/composite_test.go
  • pkg/toolchain/registry/url_test.go
  • pkg/version/reexec.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • pkg/toolchain/installer/download_test.go
  • pkg/github/client.go

Comment thread pkg/toolchain/registry/url_test.go Resolved
…ckages

Add comprehensive unit tests to improve code coverage across multiple packages:
- pkg/github/client.go: token-aware rate limit hint tests (both branches)
- pkg/github/releases.go: httptest mock server tests for fetchAllReleases
- pkg/toolchain/installer/platform.go: extract testable inner function for
  cross-platform testing (Rosetta2, Windows ARM emulation)
- pkg/version/reexec.go: add DI function fields for PR/SHA cache operations,
  enabling mock-based unit tests without GitHub API access

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ched tool lookups

GetToolWithVersion was mutating the cached Tool pointer from GetTool,
causing override fields (Asset, Format) to persist across calls for
different versions. Now operates on a shallow copy of the cached tool.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
coderabbitai[bot]
coderabbitai Bot previously approved these changes Feb 25, 2026
…test

The test was calling GetTool separately and suppressing the result with
_ = tool. Since GetToolWithVersion already fetches the tool internally,
the extra call was unnecessary.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@aknysh
Andriy Knysh (aknysh) merged commit 331929f into main Feb 26, 2026
57 checks passed
@aknysh
Andriy Knysh (aknysh) deleted the osterman/fix-toolchain-install branch February 26, 2026 02:08
@github-actions

github-actions Bot commented Mar 3, 2026

Copy link
Copy Markdown

These changes were released in v1.208.0.

@github-actions

github-actions Bot commented Mar 9, 2026

Copy link
Copy Markdown

These changes were released in v1.208.1-test.9.

@github-actions

github-actions Bot commented Mar 9, 2026

Copy link
Copy Markdown

These changes were released in v1.208.1-test.10.

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

Labels

patch A minor, backward compatible change size/xl Extra large size PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants