build: update Go to 1.27.1 and modernize the codebase (#2798)

Toolchain and CI:
- Bump go directive from 1.26.8 to 1.27.1 (go.mod)
- Use golang:1.27-alpine builder images in all Dockerfiles
- Bump golangci-lint to v2.13.2 (first release with go1.27 support)
- Add CI gate: `go fix -diff` fails when outdated Go patterns are
  detected (locally: `make check-modernize`)

Note: darwin binaries now require macOS 13 or later.

Lint fixes required by golangci-lint v2.13.2:
- goconst: ignore tests (all 436 findings were test-only; goconst
  got stricter since v2.12 and this option was added for it)
- openai.go: keep deprecated MaxTokens deliberately with a nolint
  rationale (max_tokens is the only form universally supported by
  OpenAI-compatible backends like One-API, LiteLLM, Ollama shim)
- state.go: drop always-nil flags param from appendChartVersionFlags
  (renamed to chartVersionFlags, unparam)

Modernization (go fix ./..., 62 files):
- interface{} -> any, maps.Copy, strings.SplitSeq, range-over-int,
  builtin min/max, slices.Contains/ContainsFunc/Sort, WaitGroup.Go,
  reflect.Type.Fields(), new(expr)
- exit_error.go: strings.Builder + fmt.Fprintf instead of string
  concatenation and WriteString(fmt.Sprintf(...)) (QF1012)
- chart_dependency.go: strings.CutLast for OCI dependency helpers

Signed-off-by: yxxhero <aiopsclub@163.com>
Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
yxxhero
2026-09-16 13:29:02 +08:00
committed by GitHub
co-authored by Claude
parent 88be4012b1
commit ad81e4231e
65 changed files with 710 additions and 941 deletions
+11 -22
View File
@@ -306,14 +306,8 @@ func (helm *execer) retryRepoOp(name string, op func() ([]byte, error)) ([]byte,
}
// Cap the shift exponent at 5 (2^5 = 32x already exceeds the 30x cap)
// so very large --repo-retries values can't overflow time.Duration.
shift := attempt
if shift > 5 {
shift = 5
}
backoff := repoRetryBaseBackoff * time.Duration(1<<shift)
if backoff > 30*repoRetryBaseBackoff {
backoff = 30 * repoRetryBaseBackoff
}
shift := min(attempt, 5)
backoff := min(repoRetryBaseBackoff*time.Duration(1<<shift), 30*repoRetryBaseBackoff)
helm.logger.Warnf("repo operation %q failed (%s); retry %d/%d in %v",
name, conciseError(err), attempt+1, maxRetries, backoff)
// sleepCtx returns false if interrupted by context cancellation; in that
@@ -329,8 +323,7 @@ func (helm *execer) retryRepoOp(name string, op func() ([]byte, error)) ([]byte,
// reports just the exit status, avoiding the very verbose PATH/ARGS/OUTPUT
// dump that Error() produces.
func conciseError(err error) string {
var ee ExitError
if errors.As(err, &ee) {
if ee, ok := errors.AsType[ExitError](err); ok {
return fmt.Sprintf("exit status %d", ee.ExitStatus())
}
return err.Error()
@@ -515,8 +508,7 @@ func getSupportedDependencyFlags() map[string]bool {
// Get global flags from Helm 3 cli.EnvSettings
envSettings := cliv3.New()
envType := reflect.TypeOf(*envSettings)
for i := 0; i < envType.NumField(); i++ {
field := envType.Field(i)
for field := range envType.Fields() {
if field.IsExported() {
flagName := "--" + toKebabCase(field.Name)
supported[flagName] = true
@@ -529,8 +521,7 @@ func getSupportedDependencyFlags() map[string]bool {
// Get dependency-specific flags from Helm 3 action.Dependency
dep := actionv3.NewDependency()
depType := reflect.TypeOf(*dep)
for i := 0; i < depType.NumField(); i++ {
field := depType.Field(i)
for field := range depType.Fields() {
if field.IsExported() {
flagName := "--" + toKebabCase(field.Name)
supported[flagName] = true
@@ -540,8 +531,7 @@ func getSupportedDependencyFlags() map[string]bool {
// Get global flags from Helm 4 cli.EnvSettings
envSettings := cliv4.New()
envType := reflect.TypeOf(*envSettings)
for i := 0; i < envType.NumField(); i++ {
field := envType.Field(i)
for field := range envType.Fields() {
if field.IsExported() {
flagName := "--" + toKebabCase(field.Name)
supported[flagName] = true
@@ -554,8 +544,7 @@ func getSupportedDependencyFlags() map[string]bool {
// Get dependency-specific flags from Helm 4 action.Dependency
dep := actionv4.NewDependency()
depType := reflect.TypeOf(*dep)
for i := 0; i < depType.NumField(); i++ {
field := depType.Field(i)
for field := range depType.Fields() {
if field.IsExported() {
flagName := "--" + toKebabCase(field.Name)
supported[flagName] = true
@@ -589,8 +578,8 @@ func filterDependencyUnsupportedFlags(flags []string) []string {
for _, flag := range flags {
// Extract flag name without value (e.g., "--dry-run=server" -> "--dry-run")
flagName := flag
if idx := strings.Index(flag, "="); idx != -1 {
flagName = flag[:idx]
if before, _, ok := strings.Cut(flag, "="); ok {
flagName = before
}
// Check if this flag or any prefix of it is supported
@@ -841,8 +830,8 @@ func (helm *execer) TemplateRelease(name string, chart string, flags ...string)
i++
continue
}
if strings.HasPrefix(flags[i], "--output-dir=") {
outputDir = strings.TrimPrefix(flags[i], "--output-dir=")
if after, ok := strings.CutPrefix(flags[i], "--output-dir="); ok {
outputDir = after
continue
}
filteredFlags = append(filteredFlags, flags[i])
+2 -4
View File
@@ -56,8 +56,7 @@ func TestFilterDependencyFlags_AllGlobalFlags(t *testing.T) {
}
var expectedFlags []string
for i := 0; i < envType.NumField(); i++ {
field := envType.Field(i)
for field := range envType.Fields() {
if field.IsExported() {
flagName := "--" + toKebabCase(field.Name)
expectedFlags = append(expectedFlags, flagName)
@@ -106,8 +105,7 @@ func TestFilterDependencyFlags_AllDependencyFlags(t *testing.T) {
}
var expectedFlags []string
for i := 0; i < depType.NumField(); i++ {
field := depType.Field(i)
for field := range depType.Fields() {
if field.IsExported() {
flagName := "--" + toKebabCase(field.Name)
expectedFlags = append(expectedFlags, flagName)
+9 -9
View File
@@ -6,11 +6,11 @@ import (
)
func newExitError(path string, args []string, exitStatus int, err error, stderr, combined string, stripArgsValuesOnExitError bool) ExitError {
var out string
var out strings.Builder
out += fmt.Sprintf("PATH:\n%s", Indent(path, " "))
fmt.Fprintf(&out, "PATH:\n%s", Indent(path, " "))
out += "\n\nARGS:"
out.WriteString("\n\nARGS:")
// The legacy profile is byte-identical to the historical inline logic;
// the goldens in exit_error_test.go pin its exact output.
redacted := RedactArgs(args, RedactionLegacy)
@@ -18,23 +18,23 @@ func newExitError(path string, args []string, exitStatus int, err error, stderr,
redacted = args
}
for i, a := range redacted {
out += fmt.Sprintf("\n%s", Indent(fmt.Sprintf("%d: %s (%d bytes)", i, a, len(a)), " "))
fmt.Fprintf(&out, "\n%s", Indent(fmt.Sprintf("%d: %s (%d bytes)", i, a, len(a)), " "))
}
out += fmt.Sprintf("\n\nERROR:\n%s", Indent(err.Error(), " "))
fmt.Fprintf(&out, "\n\nERROR:\n%s", Indent(err.Error(), " "))
out += fmt.Sprintf("\n\nEXIT STATUS\n%s", Indent(fmt.Sprintf("%d", exitStatus), " "))
fmt.Fprintf(&out, "\n\nEXIT STATUS\n%s", Indent(fmt.Sprintf("%d", exitStatus), " "))
if len(stderr) > 0 {
out += fmt.Sprintf("\n\nSTDERR:\n%s", Indent(stderr, " "))
fmt.Fprintf(&out, "\n\nSTDERR:\n%s", Indent(stderr, " "))
}
if len(combined) > 0 {
out += fmt.Sprintf("\n\nCOMBINED OUTPUT:\n%s", Indent(combined, " "))
fmt.Fprintf(&out, "\n\nCOMBINED OUTPUT:\n%s", Indent(combined, " "))
}
return ExitError{
Message: fmt.Sprintf("command %q exited with non-zero status:\n\n%s", path, out),
Message: fmt.Sprintf("command %q exited with non-zero status:\n\n%s", path, out.String()),
Code: exitStatus,
}
}
+1 -1
View File
@@ -23,7 +23,7 @@ type logWriter struct {
}
func (w *logWriter) Write(p []byte) (int, error) {
for _, line := range strings.Split(string(p), "\n") {
for line := range strings.SplitSeq(string(p), "\n") {
w.log.Debugf("%s%s", w.prefix, strings.TrimSpace(line))
}
return len(p), nil
+5 -7
View File
@@ -1,6 +1,9 @@
package helmexec
import "strings"
import (
"slices"
"strings"
)
// RedactionProfile selects how aggressively RedactArgs masks secret-bearing
// command-line arguments.
@@ -74,12 +77,7 @@ func RedactArgs(args []string, profile RedactionProfile) []string {
}
func isStrictNextArgFlag(arg string) bool {
for _, flag := range strictNextArgFlags {
if arg == flag {
return true
}
}
return false
return slices.Contains(strictNextArgFlags, arg)
}
// strictInlineFlag returns the flag name when arg is a single-argument secret
+2 -3
View File
@@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"io"
"maps"
"os"
"os/exec"
"path/filepath"
@@ -211,9 +212,7 @@ func LiveOutput(ctx context.Context, c *exec.Cmd, stripArgsValuesOnExitError boo
func mergeEnv(orig []string, new map[string]string) []string {
wanted := env2map(orig)
for k, v := range new {
wanted[k] = v
}
maps.Copy(wanted, new)
return map2env(wanted)
}
+1 -2
View File
@@ -158,8 +158,7 @@ func finishExecSpan(span trace.Span, isHelm bool, args []string, start time.Time
if err == nil {
return
}
var exitErr ExitError
if errors.As(err, &exitErr) {
if exitErr, ok := errors.AsType[ExitError](err); ok {
span.SetAttributes(attribute.Int("exec.exit_code", exitErr.ExitStatus()))
}
// The raw error may embed command arguments and subprocess output; keep
+1 -2
View File
@@ -105,8 +105,7 @@ func spanAttrStrings(t *testing.T, span *v1.Span, key string) []string {
// subprocess spans nest under per-release spans WITHOUT overriding the
// runner's own cancellation context (the kubedog safety valve).
func TestSpanAttachedContext(t *testing.T) {
runnerCtx, valveCancel := context.WithCancel(context.Background())
defer valveCancel()
runnerCtx := t.Context()
spanCtx, span := noop.NewTracerProvider().Tracer("test").Start(context.Background(), "release")