Skip to content

🐛 Fix four critical issues: environment merging, kubeVersion detection, lookup() with kustomize, and Helm 4 color flags - #2276

Merged
yxxhero merged 18 commits into
helmfile:mainfrom
aditmeno:fix/issues-2271-2273-2275
Nov 21, 2025
Merged

yxxhero merged 18 commits into
helmfile:mainfrom
aditmeno:fix/issues-2271-2273-2275

Conversation

@aditmeno

@aditmeno aditmeno commented Nov 19, 2025 •

Copy link
Copy Markdown
Contributor

📋 Summary

This PR fixes four critical issues that affect helmfile's core functionality and improves test infrastructure for better reliability:

  1. Base merging using WithOverride loses environment values #2273 - Environment merging from multiple bases
  2. can't probably detect environment #2275 - Kubernetes version auto-detection for helm-diff
  3. use of kustomize breaking charts that use the lookup function. #2271 - Helm lookup() function compatibility (works with or without patches)
  4. invalid color mode "--<flag>": must be one of: never, auto, always #2280 - Color flag conflict with Helm 4
  5. Test Infrastructure - Table formatting fixes and dynamic port allocation
  6. Review Fixes - Addressed all GitHub Copilot review comments

🎯 Issues Fixed

🔧 Issue #2273: Deep Merge Environments from Multiple Bases

Problem:
When using multiple base helmfiles, environment values were being completely replaced instead of deep-merged due to mergo.WithOverride introduced in PR #2228.

Impact:

  • Users lost environment configurations from base files
  • Breaking change for users with layered helmfile configurations

Solution:

  • Created custom mergeEnvironments() function for proper deep merging
  • Manually merge environment Values and Secrets slices before struct merge
  • Preserves all environment values from both base and current helmfile

Files Changed:

  • pkg/state/create.go - Added mergeEnvironments() function
  • pkg/state/create_test.go - Comprehensive test coverage

🔧 Issue #2275: Auto-Detect Kubernetes Version for helm-diff

Problem:
When helmfile runs helm-diff without specifying kubeVersion, helm-diff falls back to v1.20.0. This causes chart compatibility checks to fail for charts requiring newer Kubernetes versions.

Real-World Example:

# Chart with version requirement
kubeVersion: ">=1.25.0"

# Error without fix:
Error: chart requires kubeVersion: >=1.25.0 which is incompatible with Kubernetes v1.20.0

Root Cause:

  • flagsForDiff() was not passing kubeVersion to helm-diff plugin
  • Without --kube-version flag, helm-diff uses hardcoded v1.20.0

Solution:
✨ Auto-detect cluster version and pass to helm-diff

  • Created pkg/cluster package with DetectServerVersion() function
  • Uses k8s.io/client-go discovery API to query cluster version
  • Passes detected version via --kube-version flag to helm-diff
  • Priority: helmfile.yaml kubeVersion > auto-detected version
  • ✅ Works with both Helm 3 and Helm 4

Critical Test Case:
The upgrade scenario (second apply) that was failing in the issue:

# First apply with --skip-diff-on-install: ✅ Works
helmfile apply --skip-diff-on-install

# Second apply (triggers diff): ❌ Failed before fix, ✅ Works after fix
helmfile apply

Files Changed:

  • pkg/cluster/version.go - Cluster version detection (NEW)
  • pkg/cluster/version_test.go - Unit tests (NEW)
  • pkg/app/app.go - Integration into diff() and apply()
  • pkg/state/state.go - DiffOpts enhancement
  • pkg/state/state_kubeversion_test.go - Precedence tests (NEW)
  • test/integration/test-cases/issue-2275.sh - Integration test (NEW)

🔧 Regression Fix: Prevent Server-Side Default Normalization

Problem:
The suppress-output-line-regex integration test was failing because helm-diff was reporting "has changed, but diff is empty after suppression" for Service resources when it should have shown ipFamilyPolicy and ipFamilies fields being removed.

Root Cause:
When auto-detected kubeVersion (e.g., 1.34.0) is passed to helm-diff via --kube-version flag, helm-diff normalizes server-side defaults. This makes fields like ipFamilyPolicy and ipFamilies appear unchanged, even though they don't exist in the chart template and will be removed by the upgrade.

Example:

# Deployed Service has server-side defaults
spec:
  ipFamilyPolicy: SingleStack
  ipFamilies: 
    - IPv4

# Chart template doesn't include these fields
# Expected: Diff shows fields being removed
# Actual (before fix): "diff is empty after suppression"

Why This Happens:
helm-diff uses --kube-version to render templates and applies Kubernetes API normalization. For kubeVersion 1.34.0, it assumes ipFamilyPolicy and ipFamilies are server defaults and treats them as "unchanged" even when they're being removed.

Solution:
Added configuration option disableAutoDetectedKubeVersionForDiff to control this behavior:

Default (false): Pass auto-detected kubeVersion to helm-diff

Opt-out (true): Only pass explicit kubeVersion from helmfile.yaml

  • ✅ Prevents server-side default normalization
  • ✅ Shows real changes like ipFamilyPolicy/ipFamilies
  • ⚠️ May fail for charts requiring newer K8s versions (unless explicit kubeVersion is set)

Configuration:

helmDefaults:
  # Disable auto-detected kubeVersion to prevent normalization
  disableAutoDetectedKubeVersionForDiff: true  # false by default

releases:
- name: myrelease
  disableAutoDetectedKubeVersionForDiff: true  # Per-release override

Files Changed:

  • pkg/state/state.go - Added DisableAutoDetectedKubeVersionForDiff field and logic
  • test/integration/test-cases/suppress-output-line-regex/input/helmfile.yaml.gotmpl - Test updated to disable auto-detection

Design Decision:

  • Default behavior maintains the fix for can't probably detect environment #2275 (most users benefit)
  • Users experiencing normalization issues can opt-out via flag
  • Test explicitly disables auto-detection to verify real changes are shown

🔧 Issue #2271: Enable lookup() Function for Cluster-Requiring Commands

Problem:
When using strategicMergePatches (kustomize), Helm's lookup() function stops working. Charts like Grafana use lookup() to preserve existing resource values (e.g., PVC volumeName), which get lost when using patches.

Real-World Example from Grafana Chart:

# Grafana chart preserves PVC volume binding
volumeName: {{ (lookup "v1" "PersistentVolumeClaim" .Release.Namespace .Release.Name).spec.volumeName }}

# Without fix: volumeName gets removed → PVC recreation fails
# With fix: volumeName preserved → upgrade works smoothly

Root Cause:

  • Chartify runs helm template client-side before applying kustomize patches
  • helm template without cluster access → lookup() returns empty values
  • Kustomize then patches the broken manifests

Solution:
🎯 Enable cluster connectivity for ALL cluster-requiring commands

// Enable --dry-run=server for cluster-requiring commands
switch helmfileCommand {
case "diff", "apply", "sync", "destroy", "delete", "test", "status":
    chartifyOpts.TemplateArgs = "--dry-run=server"  // Enable cluster access
case "template", "lint", "build", "pull", "fetch", "write-values", "list", "show-dag", "deps", "repos", "cache", "init", "completion", "help", "version":
    // No cluster required - works offline
}

Updated Approach (based on Copilot feedback):

  • Previously: Only enabled --dry-run=server when patches were present
  • Now: Enabled for ALL cluster-requiring commands (diff, apply, sync, etc.)
  • Rationale: lookup() function can be used with or without patches
  • Benefit: Broader compatibility with charts using lookup() standalone

Command Behavior:

Command Cluster Required lookup() Works Offline Capable
helmfile diff ✅ Yes ✅ Yes ❌ No
helmfile apply ✅ Yes ✅ Yes ❌ No
helmfile sync ✅ Yes ✅ Yes ❌ No
helmfile template ❌ No ⚠️ Returns empty ✅ Yes
helmfile lint ❌ No ⚠️ Returns empty ✅ Yes
helmfile build ❌ No ⚠️ Returns empty ✅ Yes

Key Features:

  • ✅ Preserves offline capability for template, lint, build
  • ✅ No breaking changes to CI/CD workflows
  • ✅ Graceful degradation when cluster unavailable
  • ✅ Explicit command categorization via switch statement
  • ✅ Complete coverage: All 20+ helmfile commands properly categorized
  • ✅ Works with or without patches: Maximum flexibility

Files Changed:

  • pkg/state/state.go - Conditional --dry-run=server logic and complete command categorization
  • test/integration/test-cases/issue-2271.sh - Integration test (NEW)
  • test/integration/test-cases/issue-2271/input/* - Test chart (NEW)

🔧 Issue #2280: Color Flag Conflict with Helm 4

Problem:
In Helm 4, the --color flag is parsed by the Helm binary before being passed to plugins like helm-diff. This causes Helm to consume the next argument (e.g., --context) as the value for --color, resulting in errors.

Real-World Error:

$ helmfile diff --color --context 3

# Error:
invalid color mode "--context": must be one of: never, auto, always

Root Cause:

  • In Helm 4, --color expects a value (never/auto/always)
  • When helmfile passes --color --context 3, Helm parses it as --color="--context"
  • The --context flag gets consumed as the color value
  • helm-diff never receives the --context flag

Solution:
🎯 Use HELM_DIFF_COLOR environment variable instead of flags

For Helm 4 only:

  • Remove --color and --no-color flags from the command
  • Set HELM_DIFF_COLOR=true for --color
  • Set HELM_DIFF_COLOR=false for --no-color

The helm-diff plugin supports the HELM_DIFF_COLOR environment variable as an alternative to the flags, which prevents Helm from parsing and consuming them.

Implementation:

// In DiffRelease() for Helm 4
if helm.IsHelm4() {
    flags = helm.filterColorFlagsForHelm4(flags, env)
}

// filterColorFlagsForHelm4 removes color flags and sets env var
// Includes defensive check (Copilot suggestion)
func (helm *execer) filterColorFlagsForHelm4(flags []string, env map[string]string) []string {
    filtered := make([]string, 0, len(flags))
    
    for _, flag := range flags {
        switch flag {
        case "--color":
            if _, exists := env["HELM_DIFF_COLOR"]; !exists {
                env["HELM_DIFF_COLOR"] = "true"
            }
        case "--no-color":
            if _, exists := env["HELM_DIFF_COLOR"]; !exists {
                env["HELM_DIFF_COLOR"] = "false"
            }
        default:
            filtered = append(filtered, flag)
        }
    }
    
    return filtered
}

Behavior Note:

  • ⚠️ Changed from "last wins" to "first wins": When both --color and --no-color are present, the FIRST flag now takes precedence (due to defensive check)
  • This deviates from standard CLI conventions but is unlikely to affect real usage
  • In practice, env map is freshly created in DiffRelease(), so the defensive check is precautionary

Why Environment Variable?

  • ✅ helm-diff supports HELM_DIFF_COLOR=[true|false] as documented behavior
  • ✅ Prevents Helm 4 from parsing color flags before they reach the plugin
  • ✅ No argument consumption issues
  • ✅ Works correctly with all other flags like --context

Key Features:

  • ✅ Only applies to Helm 4 (version-specific behavior)
  • ✅ Maintains backward compatibility with Helm 3
  • ✅ Defensive check for env var (future-proof)
  • ✅ Prevents argument consumption issue completely

Files Changed:

  • pkg/helmexec/exec.go - Added filterColorFlagsForHelm4() method with defensive check
  • pkg/helmexec/exec_test.go - Comprehensive unit tests (updated for "first wins" behavior)
  • test/integration/test-cases/issue-2280.sh - Integration test (NEW)
  • test/integration/test-cases/issue-2280/input/* - Test chart (NEW)

✅ GitHub Copilot Review Comments Addressed

All review comments from the automated PR review have been resolved:

  1. Fixed pkg/cluster/version.go documentation:

    • Updated function comment to reflect error return behavior (not empty string)
    • Corrected version format comment (removed misleading "major.minor.0" reference)
    • Updated example to show actual behavior ("1.34.1" not "1.34.0")
  2. Complete command categorization in pkg/state/state.go:

    • Added fetch command to non-cluster list (from review comment)
    • Added all missing commands: write-values, list, show-dag, deps, repos, cache, init, completion, help, version
    • Added clarifying comments for command groups
    • Total: 20+ commands properly categorized
  3. Removed patches requirement for lookup():

    • Previously only enabled for commands with patches
    • Now enabled for all cluster-requiring commands
    • Addresses Copilot feedback about broader lookup() support
  4. Added defensive check for HELM_DIFF_COLOR:

    • Prevents overwriting if already set
    • Future-proof implementation
    • Note: Changes behavior from "last wins" to "first wins"
  5. Improved code documentation:

    • Clarified detectKubeVersion() return conditions
    • Added retry logic reference in getFreePort()
    • Documented design rationale for cluster connectivity

🧪 Test Infrastructure Improvements

Problem:
Multiple E2E tests were failing due to:

  • Trailing whitespace in table formatting (TestList, TestDAG)
  • Hardcoded Docker registry port conflicts (port 5000)
  • Missing sleep hack causing flaky registry tests
  • High cognitive complexity in test functions

Solutions Implemented:

1. Table Formatting Fixes

  • Created trimTrailingWhitespace() helper to remove trailing spaces/tabs
  • Optimized to only trim lines with actual whitespace (performance improvement)
  • Applied to both FormatAsTable() and printDAG() functions
  • Fixes uitable/tabwriter padding behavior for empty columns
  • Updated golden files to match new formatting

2. Dynamic Port Allocation with Retry Logic

// Before: Hardcoded port caused conflicts
port := 5000  // ❌ Conflicts with other services

// After: Kernel-allocated unused port with retry
port := getFreePort()  // ✅ Always available
// Retries up to 3 times if Docker bind fails (race condition handling)

Key Features:

  • getFreePort() - Uses net.Listen with port 0 for kernel allocation
  • waitForRegistry() - Active health polling of /v2/ endpoint (replaces sleep)
  • setupLocalDockerRegistry() - Retry logic for race condition handling
  • prepareInputFile() - Handles port substitution and path resolution
  • Port normalization replaces actual ports with $REGISTRY_PORT placeholder
  • More restrictive file permissions (0600 instead of 0644) for security

3. Code Quality Improvements

  • Extracted setupLocalDockerRegistry() helper
  • Reduced cognitive complexity from 111 to ≤110 (gocognit threshold)
  • Removed unused fakeInit struct and plugin check logic
  • Proper cleanup with t.Cleanup() functions
  • Better error messages with context wrapping

4. Path Resolution Enhancements

// Chart paths: Convert relative → absolute (input file moves to temp dir)
../../charts/raw-0.1.0 → /abs/path/to/testdata/charts/raw-0.1.0

// Postrenderer paths: Keep relative (resolved from working directory)
../../postrenderers/add-cm.bash → works for both Helm 3 & 4

Helm 3 vs Helm 4 Compatibility:

  • Helm 3: Uses postrenderer file path directly
  • Helm 4: Extracts plugin name from path
  • Both work correctly with relative paths

Files Changed:

  • pkg/app/formatters.go - Added optimized trimTrailingWhitespace()
  • pkg/app/app.go - Applied trimming to printDAG()
  • pkg/app/testdata/formatters/tableoutput - Updated golden file
  • test/e2e/template/helmfile/snapshot_test.go - Major refactoring with retry logic
  • Updated 15+ test configuration and golden files

Tests Fixed:

  • ✅ TestList - Trailing whitespace removed
  • ✅ TestDAG - Trailing whitespace removed
  • ✅ TestFormatAsTable - Golden file updated
  • ✅ TestHelmfileTemplateWithBuildCommand - All OCI tests now pass

🧪 Testing

✅ Comprehensive Test Coverage

Issue #2273:

  • Unit test: TestEnvironmentMergingWithBases
  • Scenarios: Multiple bases, overlapping values, array merging

Issue #2275:

  • Unit tests: Cluster version detection, precedence logic
  • Integration test: Chart with kubeVersion: ">=1.25.0" requirement
  • Validated upgrade scenario (critical failure case)
  • ✅ Tested with Helm 3 and Helm 4

Regression Fix:

  • Integration test: suppress-output-line-regex with disabled auto-detection
  • Verified: Server-side defaults (ipFamilyPolicy, ipFamilies) shown correctly
  • Default behavior: Auto-detection enabled (fixes can't probably detect environment #2275)
  • Opt-out behavior: Test explicitly disables to show real changes

Issue #2271:

  • Integration test: ConfigMap with lookup() function
  • Verified: Value preservation with or without patches
  • Tested: Offline template still works without cluster
  • ✅ Tested with Helm 3 and Helm 4

Issue #2280:

  • Unit tests: Test_DiffRelease_ColorFlagHelm4, Test_FilterColorFlagsForHelm4
  • Scenarios: --color to env var, --no-color to env var, mixed flags
  • Updated for "first wins" behavior with defensive check
  • Integration test: Helm 4 only, validates exact error scenario from issue
  • Verifies no "invalid color mode" error with --color --context 3
  • ✅ Tested with Helm 4

Test Infrastructure:

  • All E2E snapshot tests now pass
  • Dynamic port allocation with retry logic prevents conflicts
  • Registry health checks eliminate flaky tests
  • Golden files normalized for deterministic comparisons
  • Security improvements with restrictive file permissions

📊 Impact Analysis

✨ Benefits

  1. Environment Merging (Base merging using WithOverride loses environment values #2273)

  2. KubeVersion Detection (can't probably detect environment #2275)

    • ✅ Eliminates manual kubeVersion configuration
    • ✅ Prevents false compatibility errors
    • ✅ Seamless upgrades for modern Kubernetes clusters
  3. Server-Side Normalization Control

  4. Lookup Function (use of kustomize breaking charts that use the lookup function. #2271)

    • ✅ Works for ALL cluster-requiring commands (not just with patches)
    • ✅ Grafana and other charts with lookup() now work
    • ✅ PVC volume bindings preserved during upgrades
    • ✅ Maintains offline capability for CI/CD
    • ✅ Complete command categorization (20+ commands)
    • ✅ Maximum flexibility for chart developers
  5. Helm 4 Color Flags (invalid color mode "--<flag>": must be one of: never, auto, always #2280)

    • ✅ Fixes --color flag conflict with Helm 4
    • ✅ Prevents "invalid color mode" errors
    • ✅ Seamless Helm 4 compatibility
    • ✅ No breaking changes for Helm 3 users
    • ✅ Uses helm-diff's native environment variable support
    • ✅ Defensive check for future-proof implementation
  6. Test Infrastructure

    • ✅ More reliable tests (no port conflicts with retry logic)
    • ✅ Faster test execution (active health checks vs sleep)
    • ✅ Better code maintainability (reduced complexity)
    • ✅ Deterministic test output (port normalization)
    • ✅ Enhanced security (restrictive file permissions)
    • ✅ Performance optimizations (conditional trimming)

⚠️ Behavior Changes

Minor behavior change in Issue #2280:

  • When both --color and --no-color are present, the FIRST flag now wins instead of the LAST
  • This is due to the defensive check for HELM_DIFF_COLOR
  • Unlikely to affect real-world usage (users rarely specify conflicting flags)
  • Trade-off for more defensive, future-proof code

Otherwise backward compatible:

  • Existing helmfiles continue to work
  • New functionality is opt-in or auto-detected
  • Offline workflows preserved
  • Test infrastructure changes are internal only
  • Helm 3 behavior unchanged

🔍 Review Guide

📁 Recommended Review Order

  1. Start with tests to understand expected behavior:

  2. Review implementations in logical order:

  3. Verify integration:

    • Check test charts in test/integration/test-cases/issue-*/input/
    • Review integration test scripts
    • Validate E2E test golden file updates

🎨 Code Quality Highlights

  • ✅ Well-documented: Extensive inline comments explaining rationale
  • ✅ Type-safe: Uses proper Go idioms and error handling
  • ✅ Tested: Comprehensive unit, integration, and E2E tests
  • ✅ Maintainable: Clear separation of concerns, reduced complexity
  • ✅ Signed commits: All commits signed with GPG and DCO
  • ✅ DRY principle: Shared helper functions eliminate duplication
  • ✅ Review feedback: All Copilot review comments addressed
  • ✅ Performance: Optimized trimming, efficient retry logic
  • ✅ Security: Restrictive file permissions, proper error handling

🚀 Migration Guide

For Users Currently Affected

Issue #2273 (Environment Merging):

# Your multi-base setup now works correctly!
bases:
  - base1.yaml
  - base2.yaml

environments:
  prod:
    values:
      - prod.yaml  # Values from all bases are now preserved

Issue #2275 (KubeVersion):

# No changes needed! Auto-detection just works.
# Optional: Override if needed
helmDefaults:
  kubeVersion: "1.30.0"  # Still respected if specified

Server-Side Normalization Control:

# If you experience issues with server-side defaults being hidden:
helmDefaults:
  disableAutoDetectedKubeVersionForDiff: true  # Opt-out of auto-detection
  
releases:
- name: myapp
  # Server-side defaults like ipFamilyPolicy will now show in diffs

Issue #2271 (Lookup Function):

# lookup() now works for ALL cluster-requiring commands!
# Works with or without patches

releases:
  - name: grafana
    chart: grafana/grafana
    # lookup() works even without patches
    
  - name: app-with-patches
    chart: myapp
    strategicMergePatches:
      - patches/dns.yaml  # lookup() also works with patches

Issue #2280 (Helm 4 Color Flags):

# No changes needed! Color flags work automatically.
# Before: helmfile diff --color --context 3  ❌ Error on Helm 4
# After:  helmfile diff --color --context 3  ✅ Works on Helm 4

Test Infrastructure:
No user action needed - all improvements are internal to the test suite.


📝 Checklist


🙏 Acknowledgments

Thanks to the issue reporters for detailed reproduction steps and patience:

Thanks to GitHub Copilot for thorough code review and valuable suggestions that improved code quality, robustness, and documentation.


Fixes #2271
Fixes #2273
Fixes #2275
Fixes #2280

Problem:
When using multiple base helmfiles, environment values were being
completely replaced instead of deep-merged due to mergo.WithOverride
introduced in PR helmfile#2228.

Solution:
- Created mergeEnvironments() function for proper deep merging
- Manually merge environment Values and Secrets slices before struct merge
- Preserves all environment values from both base and current helmfile

Testing:
- Added TestEnvironmentMergingWithBases with two scenarios:
  1. Multiple bases with overlapping environment values
  2. Environment values with array merging

Fixes helmfile#2273

Signed-off-by: Aditya Menon <[email protected]>
Problem:
When helmfile runs helm-diff without specifying kubeVersion, helm-diff
falls back to v1.20.0. This causes chart compatibility checks to fail
for charts requiring newer Kubernetes versions (e.g., kubeVersion: ">=1.25.0").

Root Cause:
- flagsForDiff() was not passing kubeVersion to helm-diff plugin
- Without --kube-version flag, helm-diff uses default v1.20.0

Solution:
- Created pkg/cluster package with DetectServerVersion() function
- Auto-detect cluster version using k8s.io/client-go discovery API
- Pass detected version to helm-diff via --kube-version flag
- Priority: helmfile.yaml kubeVersion > auto-detected version
- Works with both Helm 3 and Helm 4

Implementation:
- pkg/cluster/version.go: Cluster version detection
- pkg/app/app.go: detectKubeVersion() helper used in diff() and apply()
- pkg/state/state.go: Added DetectedKubeVersion field to DiffOpts
- Integrated into flagsForDiff() with proper precedence

Testing:
- Unit tests for cluster version detection
- Unit tests for kubeVersion precedence logic
- Integration test with chart requiring Kubernetes >=1.25.0
- Tests verify upgrade scenario (critical failure case from issue)
- Validated with both Helm 3 and Helm 4

Fixes helmfile#2275

Signed-off-by: Aditya Menon <[email protected]>
Problem:
When using strategicMergePatches (kustomize), Helm's lookup() function
stops working. Charts like Grafana use lookup() to preserve existing
resource values (e.g., PVC volumeName), which get lost when using patches.

Root Cause:
- Chartify runs "helm template" to render charts before applying patches
- By default, "helm template" runs client-side without cluster access
- The lookup() function requires cluster connectivity to query resources
- Without cluster access, lookup() returns empty values

Solution:
- Pass --dry-run=server to helm template when using kustomize patches
- This enables cluster connectivity for lookup() while keeping client-side rendering
- Only applied to commands requiring cluster access (diff, apply, sync, etc.)
- Offline commands (template, lint, build) remain cluster-independent

Implementation:
- Modified processChartification() to accept helmfileCommand parameter
- Added switch-based logic to determine cluster requirement per command
- Conditionally set chartifyOpts.TemplateArgs = "--dry-run=server"
- Safe default: unknown commands assume cluster access

Command Behavior:
- helmfile diff/apply/sync: Uses --dry-run=server, lookup() works
- helmfile template/lint/build: No cluster requirement, works offline
- Charts without lookup(): Unaffected
- Charts with lookup() + cluster: Lookup values preserved correctly

Testing:
- Integration test with ConfigMap using lookup() to preserve values
- Verifies lookup works with strategicMergePatches
- Tests both with and without cluster access
- Validates offline template command still works

Fixes helmfile#2271

Signed-off-by: Aditya Menon <[email protected]>
The mergeEnvironments function always returns nil, making the error
return value unnecessary. This fixes the unparam linter warning.

- Changed function signature to not return error
- Updated call site to not handle error
- All tests still pass

Signed-off-by: Aditya Menon <[email protected]>
@aditmeno
aditmeno force-pushed the fix/issues-2271-2273-2275 branch 2 times, most recently from c5eb9a9 to 4903a7f Compare November 19, 2025 23:12
Fixes panic when base helmfile has nil Environments map.
Initialize the destination map if nil before merging to prevent
"assignment to entry in nil map" panic.

- Added nil check in mergeEnvironments to return early
- Initialize layers[0].Environments before merge if nil
- Fixes TestVisitDesiredStatesWithReleasesFiltered_Issue1008_MissingNonDefaultEnvInBase

The panic occurred when a base helmfile didn't define any environments
but a subsequent layer did. Now we properly initialize an empty map
to merge into.

Signed-off-by: Aditya Menon <[email protected]>
@yxxhero

yxxhero commented Nov 19, 2025

Copy link
Copy Markdown
Member

@aditmeno So cool. could you update helm-diff version in ci?

@aditmeno
aditmeno marked this pull request as draft November 19, 2025 23:59
Add DisableKubeVersionAutoDetection field to App struct to prevent
unit tests from connecting to real Kubernetes clusters during testing.

The kubeVersion auto-detection feature (issue helmfile#2275) was causing
unit tests to fail because:
1. Tests use mock helm implementations without real cluster access
2. Auto-detection was connecting to local minikube cluster (v1.34.0)
3. Test expectations didn't include --kube-version flag in diff keys

Solution:
- Add DisableKubeVersionAutoDetection bool field to App struct
- Check this flag in detectKubeVersion() before attempting detection
- Set flag to true in all pkg/app/*_test.go files

This ensures unit tests remain isolated and don't depend on
external cluster state while preserving auto-detection for
production use.

Signed-off-by: Aditya Menon <[email protected]>
Update helm-diff plugin from v3.14.0 to v3.14.1 across all environments:
- Dockerfiles (main, debian-stable-slim, ubuntu)
- CI workflow matrix configurations
- Integration test default version

This ensures consistency across development, testing, and production
environments.

Signed-off-by: Aditya Menon <[email protected]>
@aditmeno
aditmeno force-pushed the fix/issues-2271-2273-2275 branch 3 times, most recently from 6021371 to 55537b4 Compare November 20, 2025 00:17
This commit addresses multiple test failures and improves the testing
infrastructure for better reliability and maintainability.

Table Formatting Fixes:
- Added trimTrailingWhitespace() helper function to remove trailing
  whitespace from table output in both FormatAsTable() and printDAG()
- Fixes TestList and TestDAG failures caused by tabwriter padding
  empty columns with trailing spaces
- Updated golden file for table output test to match new behavior

E2E Test Infrastructure Improvements:
- Implemented dynamic port allocation for Docker registry tests to
  prevent port conflicts (replaced hardcoded port 5000/5001)
- Added getFreePort() function using kernel-allocated unused ports
- Added waitForRegistry() function with proper health check polling
  of Docker Registry /v2/ endpoint (replaces sleep hack)
- Added prepareInputFile() function to handle port substitution and
  path resolution when copying helmfile configs to temp directories
- Extracted setupLocalDockerRegistry() helper to reduce cognitive
  complexity from 111 to ≤110 (gocognit threshold)
- Added port normalization in test output to replace dynamic ports
  with $REGISTRY_PORT placeholder for deterministic comparisons

Test Configuration Updates:
- Updated OCI chart tests to use dynamic port allocation via
  $REGISTRY_PORT placeholder in helmfile configs
- Converted relative chart paths to absolute paths when input files
  are copied to temp directories (fixes path resolution issues)
- Left postrenderer paths as relative since they're resolved from
  working directory (works for both Helm 3 and Helm 4)

Golden File Updates:
- Updated all OCI-related test expected outputs to use $REGISTRY_PORT
  placeholder instead of hardcoded ports
- Removed trailing whitespace from issue_493 test expected output
- Updated postrenderer test outputs to reflect chart path normalization

Test Cleanup:
- Removed unused fakeInit struct and CheckHelmPlugins() call from
  snapshot tests (not needed for template/fetch/list commands)
- Removed unused imports (app, helmexec packages)

Technical Details:
- Port allocation uses net.Listen with port 0 for kernel assignment
- Registry health check polls with 500ms intervals and 30s timeout
- Chart paths: ../../charts/* → absolute paths (input file moves to temp)
- Postrenderer paths: remain relative (resolved from working directory)
- OCI cache paths normalized: oci__localhost_PORT → oci__localhost_$REGISTRY_PORT

All originally failing tests now pass:
- TestList ✓
- TestDAG ✓
- TestHelmfileTemplateWithBuildCommand (all OCI tests) ✓
- TestFormatAsTable ✓

Fixes three test failures reported in issue.

Signed-off-by: Aditya Menon <[email protected]>
@aditmeno
aditmeno force-pushed the fix/issues-2271-2273-2275 branch from af0cfd8 to d2a354e Compare November 20, 2025 01:42
Helm 3 resolves postrenderer script paths relative to the helmfile
location. When the input file is copied to a temp directory for
port substitution, relative postrenderer paths break.

Solution:
- Added postrenderersDir parameter to prepareInputFile()
- Convert ../../postrenderers/* to absolute paths for Helm 3 only
- Use existing isHelm4() function to detect Helm version
- Helm 4 extracts plugin names from paths, so works with relative

This fixes the postrenderer test failure in CI where Helm 3 could
not find the postrenderer script at the relative path.

Fixes: Error: unable to find binary at ../../postrenderers/add-cm2.bash
Signed-off-by: Aditya Menon <[email protected]>
Updated 4 remaining OCI chart tests that still had hardcoded port 5001:
- oci_chart_pull
- oci_chart_pull_once
- oci_chart_pull_once2
- oci_chart_pull_direct

Changes:
- config.yaml: Removed hardcoded port, use dynamic allocation
- input.yaml.gotmpl: Replaced localhost:5001 with localhost:$REGISTRY_PORT

This ensures all OCI chart tests use dynamic port allocation to
prevent port conflicts during parallel test execution.

Signed-off-by: Aditya Menon <[email protected]>
Problem:
The suppress-output-line-regex integration test was failing because
helm-diff was reporting "has changed, but diff is empty after suppression"
for Service resources when it should have shown ipFamilyPolicy and ipFamilies
fields being removed.

Root Cause:
When auto-detected kubeVersion (e.g., 1.34.0) is passed to helm-diff via
--kube-version flag, helm-diff normalizes server-side defaults. This makes
fields like ipFamilyPolicy and ipFamilies appear unchanged, even though they
don't exist in the chart template and will be removed by the upgrade.

After applying suppressOutputLineRegex patterns, only label changes remained
(helm.sh/chart and app.kubernetes.io/version). These were correctly suppressed,
leaving an empty diff - hence the "diff is empty after suppression" message.

Solution:
Added a new configuration option 'disableAutoDetectedKubeVersionForDiff' to allow
disabling auto-detected kubeVersion being passed to helm-diff. This prevents
helm-diff from normalizing server-side defaults when needed.

Default behavior: Pass auto-detected kubeVersion (fixes issue helmfile#2275, existing behavior)
Opt-out behavior: Set flag to true to only use explicit kubeVersion from helmfile.yaml

helmDefaults:
  disableAutoDetectedKubeVersionForDiff: true  # false by default

releases:
- name: myrelease
  disableAutoDetectedKubeVersionForDiff: true  # override per-release

Implementation:
- Added DisableAutoDetectedKubeVersionForDiff field to HelmSpec and ReleaseSpec
- Updated flagsForDiff() to check this flag before passing kubeVersion
- Default (false): pass auto-detected kubeVersion (fixes issue helmfile#2275)
- Opt-out (true): only pass explicit kubeVersion from helmfile.yaml
- Updated suppress-output-line-regex test to disable auto-detected kubeVersion

This approach:
- Maintains backward compatibility (default passes auto-detected kubeVersion)
- Fixes issue helmfile#2275 for charts requiring newer Kubernetes versions
- Allows users to opt-out when server-side normalization causes issues
- Fixes suppress-output-line-regex test regression

Signed-off-by: Aditya Menon <[email protected]>
@aditmeno
aditmeno force-pushed the fix/issues-2271-2273-2275 branch from 68b25da to 244b5d6 Compare November 20, 2025 02:46
…tectedKubeVersionForDiff field

The hash values in TestGenerateID needed to be updated because adding the
DisableAutoDetectedKubeVersionForDiff field to ReleaseSpec changed the structure's
hash representation. This is expected behavior as generateValuesID() hashes the
entire ReleaseSpec structure.

Updated all expected hash values to match the new values:
- baseline: foo-values-66f7fd6f7b
- different bytes content: foo-values-6664979cd7
- different map content: foo-values-78897dfd49
- different chart: foo-values-64b7846cb7
- different name: bar-values-576cb7ddc7
- specific ns: myns-foo-values-6c567f54c

Signed-off-by: Aditya Menon <[email protected]>
@aditmeno
aditmeno force-pushed the fix/issues-2271-2273-2275 branch from 89b75f6 to dd171b6 Compare November 20, 2025 03:07
@aditmeno
aditmeno marked this pull request as ready for review November 20, 2025 03:33
@aditmeno

Copy link
Copy Markdown
Contributor Author

@yxxhero PR is ready for review

@yxxhero

yxxhero commented Nov 20, 2025

Copy link
Copy Markdown
Member

@aditmeno LGTM, tests cases is good.

Copilot AI 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.

Pull Request Overview

Copilot reviewed 74 out of 76 changed files in this pull request and generated no new comments.

@zx8

zx8 commented Nov 20, 2025

Copy link
Copy Markdown

@aditmeno Any chance you can fix #2280 while you're poking around in this part of the code?

Sure

Nice, thank you! I think using HELM_DIFF_COLOR might be easier than trying to fiddle with the Helm 4 flag parsing. The issue I believe is that helm itself is consuming the --color flag and treating it as a string, rather than allowing helm-diff to consume the flag and treat it as a boolean.

This commit resolves issue helmfile#2280 where the --color flag causes Helm 4
to consume the next argument, resulting in errors like:
"invalid color mode '--context': must be one of: never, auto, always"

Root Cause:
In Helm 4, the --color flag is parsed by the Helm binary before being
passed to plugins like helm-diff. This causes Helm to interpret the
next argument (e.g., --context) as the value for --color.

Solution:
Remove --color and --no-color flags from helm-diff commands when using
Helm 4, and instead use the HELM_DIFF_COLOR environment variable.
The helm-diff plugin supports HELM_DIFF_COLOR=[true|false] as an
alternative to the --color/--no-color flags.

Changes:
1. Added filterColorFlagsForHelm4() function in pkg/helmexec/exec.go
   - Removes --color and --no-color flags from flags slice
   - Sets HELM_DIFF_COLOR=true for --color
   - Sets HELM_DIFF_COLOR=false for --no-color

2. Modified DiffRelease() to call filterColorFlagsForHelm4() on Helm 4

3. Added comprehensive unit tests in pkg/helmexec/exec_test.go
   - Test_DiffRelease_ColorFlagHelm4: Verifies flags are filtered
   - Test_FilterColorFlagsForHelm4: Tests all flag combinations

4. Added integration test in test/integration/test-cases/issue-2280.sh
   - Tests the exact scenario from issue helmfile#2280
   - Verifies --color and --context flags work together
   - Helm 4 only test (skipped on Helm 3)

Fixes helmfile#2280

Signed-off-by: Aditya Menon <[email protected]>
@aditmeno

Copy link
Copy Markdown
Contributor Author

@aditmeno Any chance you can fix #2280 while you're poking around in this part of the code?

Sure

Nice, thank you! I think using HELM_DIFF_COLOR might be easier than trying to fiddle with the Helm 4 flag parsing. The issue I believe is that helm itself is consuming the --color flag and treating it as a string, rather than allowing helm-diff to consume the flag and treat it as a boolean.

Yeah, the integration test failed, switching to this

Copilot AI 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.

Pull Request Overview

Copilot reviewed 74 out of 76 changed files in this pull request and generated 3 comments.

Comment thread pkg/app/formatters.go Resolved
This commit addresses minor code quality improvements suggested by
GitHub Copilot's automated review.

Changes:
1. pkg/app/formatters.go - Optimize trimTrailingWhitespace()
   - Only modify lines that actually have trailing whitespace
   - Avoids unnecessary string allocations for clean lines
   - Performance optimization for table formatting

2. test/e2e/template/helmfile/snapshot_test.go
   - Use 0600 permissions for temporary input files (was 0644)
   - Improves security by making temp files owner-only read/write
   - Prevents potential exposure of sensitive test data

   - Improve error messages in getFreePort()
   - Wrap errors with context using fmt.Errorf("%w")
   - Better error debugging when port allocation fails

   - Add retry logic to setupLocalDockerRegistry()
   - Handles race condition where port gets taken between allocation and use
   - Retries up to 3 times with new ports on "address already in use" errors
   - Fails fast on other Docker errors for better test diagnostics

All tests passing. These are non-functional improvements that enhance
code quality, performance, security, and test reliability.

Signed-off-by: Aditya Menon <[email protected]>

Copilot AI 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.

Pull Request Overview

Copilot reviewed 74 out of 76 changed files in this pull request and generated 4 comments.

Comment thread pkg/app/app.go Resolved
Comment thread pkg/state/state.go Resolved
Comment thread pkg/helmexec/exec.go Resolved
This commit addresses documentation nitpicks from GitHub Copilot's
automated review to improve code clarity and maintainability.

Changes:
1. pkg/app/app.go - Clarify detectKubeVersion() return conditions
   - Updated comment to explicitly list all three cases when empty
     string is returned: kubeVersion already set, auto-detection
     disabled, or detection fails
   - Improves function documentation clarity

2. test/e2e/template/helmfile/snapshot_test.go
   - Added reference to retry logic in getFreePort() comment
   - Points callers to setupLocalDockerRegistry() for proper race
     condition handling example
   - Better guidance for future code maintainers

3. pkg/state/state.go - Explain patches check rationale
   - Added comment explaining why --dry-run=server is only enabled
     when patches are used
   - Clarifies that this is a conservative approach to minimize
     unnecessary cluster connections
   - Documents primary use case (Grafana chart with PVC preservation)

All changes are documentation-only with no functional impact.
All tests passing.

Signed-off-by: Aditya Menon <[email protected]>
…check

This commit addresses two Copilot review suggestions to improve code
robustness and functionality.

Changes:
1. pkg/state/state.go - Remove patches requirement for lookup()
   - Previously only enabled --dry-run=server when patches were present
   - Now enables it for ALL cluster-requiring commands
   - Rationale: lookup() function can be used without patches
   - Improves compatibility with charts using lookup() standalone
   - Trade-off: Slightly more cluster connections vs broader support

2. pkg/helmexec/exec.go - Add defensive check for HELM_DIFF_COLOR
   - Only set environment variable if not already present
   - Makes code more defensive for future implementation changes
   - Note: Changes behavior from "last wins" to "first wins"
   - In practice, env map is freshly created so check is precautionary

3. pkg/helmexec/exec_test.go - Update test expectations
   - Changed test case to reflect "first wins" behavior
   - Updated test name and comment for clarity

Breaking behavior change:
- When both --color and --no-color are present, the FIRST flag now
  wins instead of the LAST flag
- This deviates from standard CLI conventions where later flags
  override earlier ones
- However, this is unlikely to affect real usage as users rarely
  specify conflicting flags

All tests passing.

Signed-off-by: Aditya Menon <[email protected]>

Copilot AI 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.

Pull Request Overview

Copilot reviewed 74 out of 76 changed files in this pull request and generated no new comments.

@zx8

zx8 commented Nov 20, 2025

Copy link
Copy Markdown

@aditmeno Any chance you can fix #2280 while you're poking around in this part of the code?

Sure

Nice, thank you! I think using HELM_DIFF_COLOR might be easier than trying to fiddle with the Helm 4 flag parsing. The issue I believe is that helm itself is consuming the --color flag and treating it as a string, rather than allowing helm-diff to consume the flag and treat it as a boolean.

Yeah, the integration test failed, switching to this

Compiled this PR locally and can confirm the issue is resolved. Thank you!

@yxxhero yxxhero left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM, thanks so much for you great works.

@yxxhero
yxxhero merged commit c8bcbcd into helmfile:main Nov 21, 2025
@aditmeno
aditmeno deleted the fix/issues-2271-2273-2275 branch November 21, 2025 01:05
@crabique

Copy link
Copy Markdown

The kubeVersion bug is actually fixed in the upstream and will be in 4.0.1 release: helm/helm#31512

@github-actions github-actions Bot locked as resolved and limited conversation to collaborators Nov 22, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

5 participants