Skip to content

fix: toolchain error handling, binary naming, and platform detection - #2027

Merged
Andriy Knysh (aknysh) merged 9 commits into
mainfrom
aknysh/windows-test-2
Jan 25, 2026
Merged

Andriy Knysh (aknysh) merged 9 commits into
mainfrom
aknysh/windows-test-2

Conversation

@aknysh

@aknysh Andriy Knysh (aknysh) commented Jan 25, 2026 •

Copy link
Copy Markdown
Member

what

  • Glamour warning suppression: Suppress confusing "Warning: unhandled element" messages from glamour markdown renderer by redirecting stdout during rendering with thread-safe mutex protection
  • Improved HTTP 404 error messages: User-friendly error messages with platform-specific hints and context instead of nested "HTTP request failed: HTTP request failed:" pattern
  • Binary naming fix for 3-segment packages: kubectl correctly named kubectl instead of kubernetes (extracts binary name from last segment of Aqua package name like kubernetes/kubernetes/kubectl) via resolveBinaryName helper
  • Pre-flight platform compatibility check: Check supported_envs from Aqua registry before attempting download, providing immediate feedback instead of waiting for HTTP 404
  • Arch-only platform matching: Handle Aqua registry supported_envs entries like amd64 which mean "any OS with this architecture" (fixes helm/helm on Windows which uses ["darwin", "linux", "amd64"])
  • Platform-specific hints: WSL hints for Windows users, Rosetta 2 hints for macOS arm64 users, Docker suggestions for Linux-only tools on macOS, QEMU hints for Linux arm64 users
  • Non-existent tool error handling: Clear "tool not in registry" error when attempting to install tools that don't exist in any configured registry (e.g., replicatedhq/replicated which exists on GitHub but is not in Aqua registry)

why

  • Users were confused by glamour warnings that appeared in terminal output during error rendering
  • HTTP 404 errors for unsupported platforms were unhelpful and didn't explain why the download failed
  • kubectl binary naming issue broke scripts expecting the kubectl binary name
  • Users wasted time waiting for downloads to fail when the tool didn't support their platform
  • helm/helm failed on Windows because amd64 in supported_envs was treated as an OS name instead of architecture
  • Platform-specific workarounds (WSL, Rosetta, Docker) weren't suggested to users
  • The distinction between "tool not found" and "platform not supported" wasn't clear

references

  • Related to Windows toolchain fixes discovered during cross-platform testing
  • Uses Aqua registry supported_envs field for platform detection
  • Test fixture: tests/fixtures/scenarios/toolchain-aqua-tools/
  • Documentation: docs/fixes/toolchain-error-handling-and-binary-naming.md

Files Changed

Category Files
Error handling errors/errors.go, toolchain/installer/download.go
Platform detection toolchain/installer/platform.go, toolchain/installer/platform_test.go
Registry toolchain/registry/registry.go, toolchain/registry/aqua/aqua.go
Glamour fix pkg/ui/markdown/custom_renderer.go
Tests tests/toolchain_aqua_tools_test.go, toolchain/installer/download_test.go
Test fixture tests/fixtures/scenarios/toolchain-aqua-tools/

Platform Matching Logic

The isPlatformMatch function handles three Aqua registry supported_envs formats:

Format Example Matches
OS only darwin Any architecture on that OS
OS/arch darwin/amd64 Exact OS and architecture
Arch only amd64 Any OS with that architecture

This correctly handles entries like helm's ["darwin", "linux", "amd64"] where amd64 means "Windows amd64 is supported".

Test Coverage

Test Platform Description
TestToolchainAquaTools_KubectlBinaryNaming All Verifies kubectl installed as kubectl NOT kubernetes
TestToolchainAquaTools_InstallAllTools All Installs cross-platform tools; kots on Linux/macOS only
TestToolchainAquaTools_WindowsKotsPlatformError Windows Verifies platform error with WSL hint
TestToolchainAquaTools_NonExistentToolError All Verifies "not in registry" error
TestIsPlatformMatch All Tests OS-only, OS/arch, and arch-only matching
TestIsKnownArch All Tests recognition of Go architecture names
TestBuildPlatformNotSupportedError All Tests error building with hints
TestFormatPlatformError All Tests user-friendly error formatting

Summary by CodeRabbit

  • New Features

    • Pre‑flight platform checks with actionable hints (WSL, Rosetta, Docker, qemu)
    • Improved binary-name resolution for multi‑segment package identifiers
  • Bug Fixes

    • Enriched HTTP 404/download errors with OS/arch context and platform guidance
    • Windows: automatic .exe handling for raw binary URLs
    • Suppressed noisy renderer warnings during output
  • Tests

    • Expanded unit/integration fixtures covering naming, platform matching, and error scenarios
  • Documentation

    • Added guidance for toolchain error handling and binary naming

✏️ Tip: You can customize this high-level summary in your review settings.

Andriy Knysh (aknysh) and others added 3 commits January 24, 2026 20:53
Add .exe handling to buildHTTPAssetURL() for HTTP type tools (like kubectl
from dl.k8s.io) to match existing behavior in buildGitHubReleaseURL().
This fixes HTTP 404 errors on Windows when downloading raw binaries.

Added comprehensive test fixture in tests/fixtures/scenarios/windows-test/
with .tool-versions, .atmos.d custom commands, and Terraform components
for Windows testing.

Related: #2002, #2012

Co-Authored-By: Claude Opus 4.5 <[email protected]>
@aknysh Andriy Knysh (aknysh) added the patch A minor, backward compatible change label Jan 25, 2026
@aknysh
Andriy Knysh (aknysh) requested review from a team as code owners January 25, 2026 07:59
@aknysh Andriy Knysh (aknysh) added the patch A minor, backward compatible change label Jan 25, 2026
@github-actions github-actions Bot added the size/xl Extra large size PR label Jan 25, 2026
@aknysh Andriy Knysh (aknysh) self-assigned this Jan 25, 2026
@mergify

mergify Bot commented Jan 25, 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.

@github-actions

github-actions Bot commented Jan 25, 2026 •

Copy link
Copy Markdown

Dependency Review

✅ No vulnerabilities or license issues found.

Scanned Files

None

@codecov

codecov Bot commented Jan 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.54545% with 9 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.44%. Comparing base (7195f58) to head (aa32aaa).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
toolchain/installer/download.go 83.87% 5 Missing ⚠️
toolchain/installer/asset.go 66.66% 1 Missing and 1 partial ⚠️
toolchain/installer/installer.go 0.00% 1 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #2027      +/-   ##
==========================================
+ Coverage   75.39%   75.44%   +0.05%     
==========================================
  Files         792      793       +1     
  Lines       73513    73666     +153     
==========================================
+ Hits        55427    55580     +153     
- Misses      14575    14578       +3     
+ Partials     3511     3508       -3     
Flag Coverage Δ
unittests 75.44% <94.54%> (+0.05%) ⬆️

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

Files with missing lines Coverage Δ
errors/errors.go 100.00% <ø> (ø)
pkg/ui/markdown/custom_renderer.go 86.04% <100.00%> (+1.83%) ⬆️
toolchain/installer/platform.go 100.00% <100.00%> (ø)
toolchain/registry/aqua/aqua.go 82.31% <100.00%> (+0.66%) ⬆️
toolchain/registry/registry.go 57.14% <ø> (ø)
toolchain/installer/asset.go 96.58% <66.66%> (-1.64%) ⬇️
toolchain/installer/installer.go 76.67% <0.00%> (-0.55%) ⬇️
toolchain/installer/download.go 84.61% <83.87%> (+0.61%) ⬆️

... and 5 files with indirect coverage changes

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

@coderabbitai

coderabbitai Bot commented Jan 25, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds platform-aware tool installation: pre-flight platform checks, platform-aware error messages/hints, Aqua package binary-name resolution for multi-segment names, enhanced 404/download error construction with OS/arch context, Windows .exe handling for HTTP binaries, and stdout suppression during markdown rendering.

Changes

Cohort / File(s) Summary
Platform Support Validation
toolchain/installer/platform.go, toolchain/installer/platform_test.go
Adds PlatformError, CheckPlatformSupport, isPlatformMatch, buildPlatformHints, and related helpers to validate tool SupportedEnvs and produce OS/arch-specific hints (WSL, Rosetta, Docker, qemu).
Installer Integration
toolchain/installer/installer.go, toolchain/install_test.go
Invokes pre-flight CheckPlatformSupport before downloads; test gate updated with requiresNetwork skip in short mode.
Registry Data Model & Binary Resolution
toolchain/registry/registry.go, toolchain/registry/aqua/aqua.go, toolchain/registry/aqua/aqua_test.go
Adds SupportedEnvs to Tool; Aqua parsing now carries Name and SupportedEnvs, introduces extractBinaryNameFromPackageName and resolveBinaryName to derive correct binary names (e.g., kubectl).
Download & Error Handling
toolchain/installer/download.go, toolchain/installer/download_test.go, errors/errors.go
Replaces generic fallback error with buildDownloadNotFoundError, addPlatformSpecificHints, buildPlatformNotSupportedError, and wrappers (getOS, getArch); adds ErrToolPlatformNotSupported sentinel and tests for 404/platform error behaviors.
Asset URL & Windows Handling
toolchain/installer/asset.go, toolchain/installer/asset_test.go
Template execution errors handled explicitly; append .exe for non-archive HTTP URLs on Windows; tests added for Windows .exe behavior and archive preservation.
UI Rendering
pkg/ui/markdown/custom_renderer.go
Redirects stdout to suppress glamour warnings during markdown rendering (mutex-protected).
Tests / Fixtures / Snapshots
tests/fixtures/scenarios/toolchain-aqua-tools/*, tests/toolchain_aqua_tools_test.go, tests/snapshots/TestCLICommands_atmos_toolchain_install_non-existent_tool.stdout.golden
Adds Aqua toolchain fixtures and extensive integration tests for binary naming, execution, cross-platform install, Windows-specific cases, and non-existent-tool errors; removes glamour warning lines from golden snapshot.
Windows Test Skips
pkg/provisioner/workdir/clean_test.go
Adds runtime.GOOS guards to skip permission-related tests on Windows.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Client
    participant Installer as Installer
    participant Registry as Registry
    participant Platform as PlatformCheck
    participant ErrorBuilder as ErrorBuilder

    Client->>Installer: installFromTool(tool)
    Installer->>Registry: read tool metadata (SupportedEnvs, Name)
    Installer->>Platform: CheckPlatformSupport(tool)
    Platform->>Platform: getOS/getArch, isPlatformMatch()
    alt platform matches
        Platform-->>Installer: nil
        Installer->>Installer: BuildAssetURL, BuildAssetPath
        Installer->>Client: download/install binary
    else platform unsupported
        Platform->>ErrorBuilder: buildPlatformHints()
        ErrorBuilder-->>Platform: hints
        Platform-->>Installer: PlatformError (with hints)
        Installer-->>Client: formatted platform-not-supported error (WSL/Rosetta/Docker/qemu hints)
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

minor

Suggested reviewers

  • osterman
🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 58.33% 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 and specifically summarizes the main changes: toolchain error handling improvements, binary naming fixes, and platform detection implementation.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch aknysh/windows-test-2

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: 3

🤖 Fix all issues with AI agents
In `@pkg/ui/markdown/custom_renderer.go`:
- Around line 205-221: The Render method currently mutates process-wide
os.Stdout (oldStdout, devNull) which is racy under concurrent use; protect the
swap by introducing a package-level sync.Mutex (e.g., stdoutMutex) and lock it
around opening /dev/null, replacing os.Stdout, and restoring it in the defer to
serialize swaps, and open /dev/null with os.OpenFile(os.DevNull, os.O_WRONLY, 0)
instead of os.Open so it is write-only; ensure the defer both restores os.Stdout
and closes devNull and preserve existing err handling around the open.

In
`@tests/fixtures/scenarios/complete/components/terraform/infra/vpc-flow-logs-bucket/README.md`:
- Line 94: The markdown list item "*
[cloudposse/terraform-aws-components](https://github.com/cloudposse/terraform-aws-components/tree/master/modules/vpc-flow-logs-bucket)
- Cloud Posse's upstream component" is indented by two spaces causing MD007
failures; remove the two leading spaces so the list marker starts at column zero
(i.e., make the line a top-level list item in README.md) to satisfy
markdownlint.

In `@toolchain/installer/asset_test.go`:
- Around line 701-708: The test hardcodes the Windows architecture
("windows/amd64") when asserting the expected URL, which will fail on non-amd64
machines; update the Windows branch to build the expected URL using
runtime.GOARCH (e.g., construct expected :=
"https://dl.k8s.io/v1.31.4/bin/windows/" + runtime.GOARCH + "/kubectl.exe") and
assert url == expected while keeping the .exe suffix check; modify the assertion
that currently references the literal
"https://dl.k8s.io/v1.31.4/bin/windows/amd64/kubectl.exe" to use the
runtime.GOARCH-based expected value instead.
🧹 Nitpick comments (6)
toolchain/registry/aqua/aqua.go (1)

434-461: Consider extracting binary name resolution helper.

The 3-step fallback logic (lines 439-445) duplicates the pattern in resolveVersionOverrides (lines 269-275). A shared helper would reduce duplication.

Suggested helper
// resolveBinaryName determines the binary name using Aqua's resolution order.
func resolveBinaryName(binaryName, packageName, repoName string) string {
	if binaryName != "" {
		return binaryName
	}
	if name := extractBinaryNameFromPackageName(packageName); name != "" {
		return name
	}
	return repoName
}
toolchain/installer/download.go (1)

202-214: Potential duplication with buildPlatformHints in platform.go.

This function and buildPlatformHints in platform.go both generate platform-specific hints but with slightly different coverage. Consider consolidating to a single source of truth to avoid drift. For now, this is acceptable since the contexts differ (post-404 vs pre-flight check).

toolchain/installer/platform_test.go (2)

137-148: Prefer strings.Contains over custom substring search.

This custom implementation is overly complex and reimplements stdlib functionality.

♻️ Suggested simplification
-func contains(s, substr string) bool {
-	return len(s) > 0 && len(substr) > 0 && (s == substr || len(s) > len(substr) && (s[:len(substr)] == substr || s[len(s)-len(substr):] == substr || findSubstring(s, substr)))
-}
-
-func findSubstring(s, substr string) bool {
-	for i := 0; i <= len(s)-len(substr); i++ {
-		if s[i:i+len(substr)] == substr {
-			return true
-		}
-	}
-	return false
-}
+func contains(s, substr string) bool {
+	return strings.Contains(s, substr)
+}

You'll need to add "strings" to imports.


102-110: Redundant condition in hint search loop.

The check assert.NotEmpty(t, hint) && len(hint) > 0 is redundant—len(hint) > 0 already covers non-empty.

♻️ Simplified loop
-	for _, hint := range hints {
-		if assert.NotEmpty(t, hint) && len(hint) > 0 {
-			if contains(hint, "WSL") {
-				foundWSL = true
-			}
-		}
-	}
+	for _, hint := range hints {
+		if contains(hint, "WSL") {
+			foundWSL = true
+		}
+	}
tests/toolchain_aqua_tools_test.go (1)

149-163: Consider extracting version constants for maintainability.

Tool versions like "1.31.4" and "0.17.0" appear multiple times. Extracting to constants at the top of the file would make updates easier and reduce risk of inconsistency.

toolchain/installer/platform.go (1)

20-25: Consider removing perf.Track from Error() method.

The Error() method may be called multiple times (e.g., during logging, error wrapping, display). Performance tracking here adds overhead with limited diagnostic value. Reserve perf.Track for heavier operations.

Comment thread pkg/ui/markdown/custom_renderer.go Resolved
Comment thread toolchain/installer/asset_test.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: 1

🤖 Fix all issues with AI agents
In `@docs/fixes/toolchain-error-handling-and-binary-naming.md`:
- Line 682: The markdown contains a bare URL in the table cell
("https://github.com/replicatedhq/replicated"); update that cell so the URL is
wrapped in angle brackets (<https://github.com/replicatedhq/replicated>) to
satisfy static analysis and proper Markdown linking—edit the table row where the
GitHub repo URL appears and replace the plain URL with the angle-bracketed form.
🧹 Nitpick comments (1)
toolchain/installer/platform.go (1)

87-103: Consider hoisting the known architectures map to package level.

The map is allocated on each call. For the typical small supported_envs lists, this isn't a performance concern, but a package-level var would be cleaner.

♻️ Optional refactor
+// knownArchs contains Go's architecture identifiers.
+var knownArchs = map[string]bool{
+	"amd64": true, "arm64": true, "386": true, "arm": true,
+	"ppc64": true, "ppc64le": true, "mips": true, "mipsle": true,
+	"mips64": true, "s390x": true, "riscv64": true,
+}
+
 // isKnownArch returns true if the string is a known Go architecture name.
 func isKnownArch(s string) bool {
-	knownArchs := map[string]bool{
-		"amd64":   true,
-		"arm64":   true,
-		"386":     true,
-		"arm":     true,
-		"ppc64":   true,
-		"ppc64le": true,
-		"mips":    true,
-		"mipsle":  true,
-		"mips64":  true,
-		"s390x":   true,
-		"riscv64": true,
-	}
 	return knownArchs[s]
 }

@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

🤖 Fix all issues with AI agents
In `@docs/fixes/toolchain-error-handling-and-binary-naming.md`:
- Around line 46-47: Update the documentation text to refer to the portable
os.DevNull constant instead of the platform-specific path "/dev/null": in the
discussion of glamour rendering (see pkg/ui/markdown/custom_renderer.go and the
glamor/glamour rendering section), change the wording from “redirect stdout to
`/dev/null`” to “redirect stdout to os.DevNull” so the doc matches the
implementation and is correct on Windows.

coderabbitai[bot]
coderabbitai Bot previously approved these changes Jan 25, 2026
Comment thread tests/toolchain_aqua_tools_test.go Resolved
Comment thread tests/toolchain_aqua_tools_test.go Resolved
Comment thread tests/toolchain_aqua_tools_test.go Resolved
@aknysh
Andriy Knysh (aknysh) merged commit c90352d into main Jan 25, 2026
57 checks passed
@aknysh
Andriy Knysh (aknysh) deleted the aknysh/windows-test-2 branch January 25, 2026 23:17
@github-actions

Copy link
Copy Markdown

These changes were released in v1.204.1-rc.6.

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