ci: enable errcheck linter and fix unchecked errors

Signed-off-by: thev1ndu <itsthw9@gmail.com>
pull/32512/head
thev1ndu 2 months ago
parent ae877c8bfb
commit 45966219b7

@ -28,6 +28,7 @@ linters:
- contextcheck
- depguard
- dupl
- errcheck
- errorlint
- exhaustive
- fatcontext

@ -30,7 +30,7 @@ func FuzzMetadataValidate(f *testing.F) {
if err != nil {
t.Skip()
}
md.Validate()
_ = md.Validate()
})
}
@ -43,6 +43,6 @@ func FuzzDependencyValidate(f *testing.F) {
if err != nil {
t.Skip()
}
d.Validate()
_ = d.Validate()
})
}

@ -42,23 +42,23 @@ func TestInvalidCrdsDir(t *testing.T) {
func TestCrdWithEmptyDocument(t *testing.T) {
chartDir := t.TempDir()
os.WriteFile(filepath.Join(chartDir, "Chart.yaml"), []byte(
require.NoError(t, os.WriteFile(filepath.Join(chartDir, "Chart.yaml"), []byte(
`apiVersion: v1
name: test
version: 0.1.0
`), 0o644)
`), 0o644))
// CRD with comments before --- (creates empty document)
crdsDir := filepath.Join(chartDir, "crds")
os.Mkdir(crdsDir, 0o755)
os.WriteFile(filepath.Join(crdsDir, "test.yaml"), []byte(
require.NoError(t, os.Mkdir(crdsDir, 0o755))
require.NoError(t, os.WriteFile(filepath.Join(crdsDir, "test.yaml"), []byte(
`# Comments create empty document
---
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: test.example.io
`), 0o644)
`), 0o644))
linter := support.Linter{ChartDir: chartDir}
Crds(&linter)

@ -82,7 +82,9 @@ func validateNoDeprecations(resource *k8sYamlStruct, kubeVersion *common.KubeVer
func resourceToRuntimeObject(resource *k8sYamlStruct) (runtime.Object, error) {
scheme := runtime.NewScheme()
kscheme.AddToScheme(scheme)
if err := kscheme.AddToScheme(scheme); err != nil {
return nil, err
}
gvk := schema.FromAPIVersionAndKind(resource.APIVersion, resource.Kind)
out, err := scheme.New(gvk)

@ -70,8 +70,8 @@ var (
// namespaces, partial templates
func TestTemplateIntegrationHappyPath(t *testing.T) {
// Rename file so it gets ignored by the linter
os.Rename(wrongTemplatePath, ignoredTemplatePath)
defer os.Rename(ignoredTemplatePath, wrongTemplatePath)
require.NoError(t, os.Rename(wrongTemplatePath, ignoredTemplatePath))
defer func() { _ = os.Rename(ignoredTemplatePath, wrongTemplatePath) }()
linter := support.Linter{ChartDir: templateTestBasedir}
Templates(&linter, values, namespace, strict)

@ -274,7 +274,8 @@ icon: https://example.com/64x64.png
w.Close()
var text bytes.Buffer
io.Copy(&text, r)
_, err = io.Copy(&text, r)
require.NoError(t, err)
assert.Empty(t, text.String(), "Expected no message to Stderr, got %s", text.String())
}

@ -106,7 +106,7 @@ func TestCreate_Overwrite(t *testing.T) {
dir := filepath.Join(tdir, "foo")
tplname := filepath.Join(dir, "templates", "hpa.yaml")
writeFile(tplname, []byte("FOO"))
require.NoError(t, writeFile(tplname, []byte("FOO")))
// Now re-run the create
Stderr = &errlog

@ -142,7 +142,9 @@ func (c *Client) SearchWithContext(ctx context.Context, term string) ([]SearchRe
result := &searchResponse{}
json.NewDecoder(res.Body).Decode(result)
if err := json.NewDecoder(res.Body).Decode(result); err != nil {
return nil, err
}
return result.Data, nil
}

@ -137,26 +137,26 @@ func mockOCIRegistryWithArtifactType(t *testing.T, pluginName string) (*httptest
w.Header().Set("Docker-Distribution-API-Version", "registry/2.0")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte("{}"))
_, _ = w.Write([]byte("{}"))
case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/manifests/") && strings.Contains(r.URL.Path, pluginName):
// Return manifest
w.Header().Set("Content-Type", ocispec.MediaTypeImageManifest)
w.Header().Set("Docker-Content-Digest", manifestDigest)
w.WriteHeader(http.StatusOK)
w.Write(manifestData)
_, _ = w.Write(manifestData)
case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/blobs/"+layerDigest):
// Return layer data
w.Header().Set("Content-Type", "application/vnd.oci.image.layer.v1.tar")
w.WriteHeader(http.StatusOK)
w.Write(pluginData)
_, _ = w.Write(pluginData)
case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/blobs/"+configDigest):
// Return config data
w.Header().Set("Content-Type", "application/vnd.oci.empty.v1+json")
w.WriteHeader(http.StatusOK)
w.Write(configData)
_, _ = w.Write(configData)
default:
w.WriteHeader(http.StatusNotFound)

@ -255,7 +255,9 @@ func (r *SubprocessPluginRuntime) runPostrenderer(ctx context.Context, input *In
go func() {
defer stdin.Close()
io.Copy(stdin, msg.Manifests)
if _, err := io.Copy(stdin, msg.Manifests); err != nil {
slog.Debug("failed to copy manifests to plugin stdin", slog.String("pluginName", r.metadata.Name), slog.String("error", err.Error()))
}
}()
postRendered := &bytes.Buffer{}

@ -56,7 +56,7 @@ func mockSubprocessCLIPluginErrorExit(t *testing.T, pluginName string, exitCode
data, err := yaml.Marshal(md)
require.NoError(t, err)
os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), data, 0o644)
require.NoError(t, os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), data, 0o644))
return &SubprocessPluginRuntime{
metadata: md,

@ -593,7 +593,7 @@ func (i *Install) failRelease(rel *release.Release, err error) (*release.Release
}
return rel, fmt.Errorf("release %s failed, and has been uninstalled due to rollback-on-failure being set: %w", i.ReleaseName, err)
}
i.recordRelease(rel) // Ignore the error, since we have another error to deal with.
_ = i.recordRelease(rel) // Ignore the error, since we have another error to deal with.
return rel, err
}

@ -109,7 +109,9 @@ func (r *ReleaseTesting) Run(name string) (ri.Releaser, ExecuteShutdownFunc, err
shutdown, err := r.cfg.execHookWithDelayedShutdown(rel, release.HookTest, kube.StatusWatcherStrategy, r.WaitOptions, r.Timeout, serverSideApply)
if err != nil {
rel.Hooks = append(skippedHooks, rel.Hooks...)
r.cfg.Releases.Update(reli)
if updateErr := r.cfg.Releases.Update(reli); updateErr != nil {
return reli, shutdown, errors.Join(err, updateErr)
}
return reli, shutdown, err
}

@ -107,7 +107,9 @@ func (s *Show) Run(chartpath string) (string, error) {
if err != nil {
return "", fmt.Errorf("error parsing jsonpath %s: %w", s.JSONPathTemplate, err)
}
printer.Execute(&out, s.chart.Values)
if err := printer.Execute(&out, s.chart.Values); err != nil {
return "", fmt.Errorf("error executing jsonpath %s: %w", s.JSONPathTemplate, err)
}
} else {
for _, f := range s.chart.Raw {
if f.Name == chartutil.ValuesfileName {

@ -387,13 +387,15 @@ func (u *Upgrade) performUpgrade(ctx context.Context, originalRelease, upgradedR
return nil, fmt.Errorf("unable to continue with update: %w", err)
}
toBeUpdated.Visit(func(r *resource.Info, err error) error {
if err := toBeUpdated.Visit(func(r *resource.Info, err error) error {
if err != nil {
return err
}
current.Append(r)
return nil
})
}); err != nil {
return nil, err
}
if isDryRun(u.DryRunStrategy) {
u.cfg.Logger().Debug("dry run for release", "name", upgradedRelease.Name)

@ -27,6 +27,7 @@ import (
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
k8sversion "k8s.io/apimachinery/pkg/util/version"
helmversion "helm.sh/helm/v4/internal/version"
@ -130,8 +131,8 @@ func allKnownVersions() VersionSet {
// We should register the built in extension APIs as well so CRDs are
// supported in the default version set. This has caused problems with `helm
// template` in the past, so let's be safe
apiextensionsv1beta1.AddToScheme(scheme.Scheme)
apiextensionsv1.AddToScheme(scheme.Scheme)
utilruntime.Must(apiextensionsv1beta1.AddToScheme(scheme.Scheme))
utilruntime.Must(apiextensionsv1.AddToScheme(scheme.Scheme))
groups := scheme.Scheme.PrioritizedVersionsAllGroups()
vs := make(VersionSet, 0, len(groups))

@ -206,7 +206,7 @@ func TestHTTPURLLoader_Load(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"type": "object", "properties": {"name": {"type": "string"}}}`))
_, _ = w.Write([]byte(`{"type": "object", "properties": {"name": {"type": "string"}}}`))
}))
defer server.Close()

@ -166,7 +166,9 @@ func LoadArchiveFiles(in io.Reader) ([]*BufferedFile, error) {
// of this is invoking `helm template values.yaml mychart` which would otherwise produce a confusing error
// if we didn't check for this.
func EnsureArchive(name string, raw *os.File) error {
defer raw.Seek(0, 0) // reset read offset to allow archive loading to proceed.
defer func() {
_, _ = raw.Seek(0, 0) // reset read offset to allow archive loading to proceed.
}()
// Check the file format to give us a chance to provide the user with more actionable feedback.
buffer := make([]byte, 512)

@ -30,7 +30,7 @@ func FuzzMetadataValidate(f *testing.F) {
if err != nil {
t.Skip()
}
md.Validate()
_ = md.Validate()
})
}
@ -43,6 +43,6 @@ func FuzzDependencyValidate(f *testing.F) {
if err != nil {
t.Skip()
}
d.Validate()
_ = d.Validate()
})
}

@ -42,23 +42,23 @@ func TestInvalidCrdsDir(t *testing.T) {
func TestCrdWithEmptyDocument(t *testing.T) {
chartDir := t.TempDir()
os.WriteFile(filepath.Join(chartDir, "Chart.yaml"), []byte(
require.NoError(t, os.WriteFile(filepath.Join(chartDir, "Chart.yaml"), []byte(
`apiVersion: v1
name: test
version: 0.1.0
`), 0o644)
`), 0o644))
// CRD with comments before --- (creates empty document)
crdsDir := filepath.Join(chartDir, "crds")
os.Mkdir(crdsDir, 0o755)
os.WriteFile(filepath.Join(crdsDir, "test.yaml"), []byte(
require.NoError(t, os.Mkdir(crdsDir, 0o755))
require.NoError(t, os.WriteFile(filepath.Join(crdsDir, "test.yaml"), []byte(
`# Comments create empty document
---
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: test.example.io
`), 0o644)
`), 0o644))
linter := support.Linter{ChartDir: chartDir}
Crds(&linter)

@ -82,7 +82,9 @@ func validateNoDeprecations(resource *k8sYamlStruct, kubeVersion *common.KubeVer
func resourceToRuntimeObject(resource *k8sYamlStruct) (runtime.Object, error) {
scheme := runtime.NewScheme()
kscheme.AddToScheme(scheme)
if err := kscheme.AddToScheme(scheme); err != nil {
return nil, err
}
gvk := schema.FromAPIVersionAndKind(resource.APIVersion, resource.Kind)
out, err := scheme.New(gvk)

@ -71,8 +71,8 @@ var (
// namespaces, partial templates
func TestTemplateIntegrationHappyPath(t *testing.T) {
// Rename file so it gets ignored by the linter
os.Rename(wrongTemplatePath, ignoredTemplatePath)
defer os.Rename(ignoredTemplatePath, wrongTemplatePath)
require.NoError(t, os.Rename(wrongTemplatePath, ignoredTemplatePath))
defer func() { _ = os.Rename(ignoredTemplatePath, wrongTemplatePath) }()
linter := support.Linter{ChartDir: templateTestBasedir}
Templates(

@ -316,7 +316,8 @@ icon: https://example.com/64x64.png
w.Close()
var text bytes.Buffer
io.Copy(&text, r)
_, err = io.Copy(&text, r)
require.NoError(t, err)
assert.Empty(t, text.String(), "Expected no message to Stderr, got %s", text.String())
}

@ -104,7 +104,7 @@ func TestCreate_Overwrite(t *testing.T) {
dir := filepath.Join(tdir, "foo")
tplname := filepath.Join(dir, "templates", "hpa.yaml")
writeFile(tplname, []byte("FOO"))
require.NoError(t, writeFile(tplname, []byte("FOO")))
// Now re-run the create
Stderr = &errlog

@ -55,7 +55,8 @@ func makeTestChartArchive(t *testing.T, chartName, sourceDir string) *bytes.Buff
data, err := fs.ReadFile(dir, relPath)
require.NoError(t, err)
tw.Write(data)
_, err = tw.Write(data)
require.NoError(t, err)
}
require.NoError(t, fs.WalkDir(dir, ".", func(path string, d os.DirEntry, walkErr error) error {

@ -131,7 +131,7 @@ func TestEnvSettings(t *testing.T) {
settings := New()
settings.AddFlags(flags)
flags.Parse(strings.Split(tt.args, " "))
require.NoError(t, flags.Parse(strings.Split(tt.args, " ")))
assert.Equal(t, tt.debug, settings.Debug, "debug")
assert.Equal(t, tt.ns, settings.Namespace(), "namespace")

@ -208,7 +208,7 @@ func TestReadFile(t *testing.T) {
testData := []byte("stdin test data")
go func() {
defer w.Close()
w.Write(testData)
_, _ = w.Write(testData)
}()
// Test the function

@ -32,7 +32,7 @@ import (
func checkFileCompletion(t *testing.T, cmdName string, shouldBePerformed bool) {
t.Helper()
storage := storageFixture()
storage.Create(&release.Release{
require.NoError(t, storage.Create(&release.Release{
Name: "myrelease",
Info: &release.Info{Status: common.StatusDeployed},
Chart: &chart.Chart{
@ -42,7 +42,7 @@ func checkFileCompletion(t *testing.T, cmdName string, shouldBePerformed bool) {
},
},
Version: 1,
})
}))
testcmd := fmt.Sprintf("__complete %s ''", cmdName)
_, out, err := executeActionCommandC(storage, testcmd)

@ -88,7 +88,7 @@ func newCreateCmd(out io.Writer) *cobra.Command {
cmd.Flags().StringVar(&o.chartAPIVersion, "chart-api-version", chart.APIVersionV2, "chart API version to use (v2 or v3)")
if !gates.ChartV3.IsEnabled() {
cmd.Flags().MarkHidden("chart-api-version")
_ = cmd.Flags().MarkHidden("chart-api-version")
}
return cmd

@ -105,7 +105,7 @@ func TestCreateStarterCmd(t *testing.T) {
// Create a starter using the appropriate chartutil
starterchart := helmpath.DataPath("starters")
os.MkdirAll(starterchart, 0o755)
require.NoError(t, os.MkdirAll(starterchart, 0o755))
var err error
var dest string
if tt.chartAPIVersion == "v3" {

@ -38,7 +38,7 @@ func TestDependencyBuildCmd(t *testing.T) {
defer srv.Stop()
rootDir := srv.Root()
srv.LinkIndices()
require.NoError(t, srv.LinkIndices())
ociSrv, err := repotest.NewOCIServer(t, srv.Root())
require.NoError(t, err)

@ -69,7 +69,7 @@ func newDocsCmd(out io.Writer) *cobra.Command {
f.StringVar(&o.docTypeString, "type", "markdown", "the type of documentation to generate (markdown, man, bash)")
f.BoolVar(&o.generateHeaders, "generate-headers", false, "generate standard headers for markdown files")
cmd.RegisterFlagCompletionFunc("type", func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
_ = cmd.RegisterFlagCompletionFunc("type", func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
return []string{"bash", "man", "markdown"}, cobra.ShellCompDirectiveNoFileComp
})

@ -278,7 +278,7 @@ func TestCmdGetDryRunFlagStrategy(t *testing.T) {
Use: "helm",
}
addDryRunFlag(cmd)
cmd.Flags().Parse([]string{"helm", tc.DryRunFlagArg})
require.NoError(t, cmd.Flags().Parse([]string{"helm", tc.DryRunFlagArg}))
t.Run(name, func(t *testing.T) {
dryRunStrategy, err := cmdGetDryRunFlagStrategy(cmd, tc.IsTemplate)

@ -188,7 +188,7 @@ func addInstallFlags(cmd *cobra.Command, f *pflag.FlagSet, client *action.Instal
f.BoolVar(&client.CreateNamespace, "create-namespace", false, "create the release namespace if not present")
f.BoolVar(&client.ForceReplace, "force-replace", false, "force resource updates by replacement")
f.BoolVar(&client.ForceReplace, "force", false, "deprecated")
f.MarkDeprecated("force", "use --force-replace instead")
_ = f.MarkDeprecated("force", "use --force-replace instead")
f.BoolVar(&client.ForceConflicts, "force-conflicts", false, "if set server-side apply will force changes against conflicts")
f.BoolVar(&client.ServerSideApply, "server-side", true, "object updates run in the server instead of the client")
f.BoolVar(&client.DisableHooks, "no-hooks", false, "prevent hooks from running during install")
@ -203,7 +203,7 @@ func addInstallFlags(cmd *cobra.Command, f *pflag.FlagSet, client *action.Instal
f.BoolVar(&client.DisableOpenAPIValidation, "disable-openapi-validation", false, "if set, the installation process will not validate rendered templates against the Kubernetes OpenAPI Schema")
f.BoolVar(&client.RollbackOnFailure, "rollback-on-failure", false, "if set, Helm will rollback (uninstall) the installation upon failure. The --wait flag will be default to \"watcher\" if --rollback-on-failure is set")
f.BoolVar(&client.RollbackOnFailure, "atomic", false, "deprecated")
f.MarkDeprecated("atomic", "use --rollback-on-failure instead")
_ = f.MarkDeprecated("atomic", "use --rollback-on-failure instead")
f.BoolVar(&client.SkipCRDs, "skip-crds", false, "if set, no CRDs will be installed. By default, CRDs are installed if not already present")
f.BoolVar(&client.SubNotes, "render-subchart-notes", false, "if set, render subchart notes along with the parent")
f.BoolVar(&client.SkipSchemaValidation, "skip-schema-validation", false, "if set, disables JSON schema validation")

@ -66,7 +66,7 @@ func newLintCmd(out io.Writer) *cobra.Command {
if client.WithSubcharts {
for _, p := range paths {
filepath.Walk(filepath.Join(p, "charts"), func(path string, info os.FileInfo, _ error) error {
if err := filepath.Walk(filepath.Join(p, "charts"), func(path string, info os.FileInfo, _ error) error {
if info != nil {
if info.Name() == "Chart.yaml" {
paths = append(paths, filepath.Dir(path))
@ -75,7 +75,9 @@ func newLintCmd(out io.Writer) *cobra.Command {
}
}
return nil
})
}); err != nil {
return err
}
}
}

@ -100,11 +100,9 @@ func newListCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
switch outputFlag.Value.String() {
case "json":
output.EncodeJSON(out, names)
return nil
return output.EncodeJSON(out, names)
case "yaml":
output.EncodeYAML(out, names)
return nil
return output.EncodeYAML(out, names)
case "table":
for _, res := range results {
fmt.Fprintln(out, res.Name)

@ -143,8 +143,10 @@ func readLine(prompt string, silent bool) (string, error) {
if err != nil {
return "", err
}
term.DisableEcho(fd, state)
defer term.RestoreTerminal(fd, state)
if err := term.DisableEcho(fd, state); err != nil {
return "", err
}
defer func() { _ = term.RestoreTerminal(fd, state) }()
}
reader := bufio.NewReader(os.Stdin)

@ -57,7 +57,7 @@ func TestReleaseTestNotesHandling(t *testing.T) {
// Set up storage
store := storageFixture()
store.Create(rel)
require.NoError(t, store.Create(rel))
// Set up action configuration properly
actionConfig := &action.Configuration{

@ -131,7 +131,7 @@ func (o *repoAddOptions) run(out io.Writer) error {
defer cancel()
locked, err := fileLock.TryLockContext(lockCtx, time.Second)
if err == nil && locked {
defer fileLock.Unlock()
defer func() { _ = fileLock.Unlock() }()
}
if err != nil {
return err

@ -101,7 +101,9 @@ func index(dir, url, mergeTo string, json bool) error {
var i2 *repo.IndexFile
if _, err := os.Stat(mergeTo); errors.Is(err, fs.ErrNotExist) {
i2 = repo.NewIndexFile()
writeIndexFile(i2, mergeTo, json)
if err := writeIndexFile(i2, mergeTo, json); err != nil {
return err
}
} else {
i2, err = repo.LoadIndexFile(mergeTo)
if err != nil {

@ -62,7 +62,7 @@ func TestRepoIndexCmd(t *testing.T) {
// Test with `--json`
c.ParseFlags([]string{"--json", "true"})
require.NoError(t, c.ParseFlags([]string{"--json", "true"}))
require.NoError(t, c.RunE(c, []string{dir}))
b, err = os.ReadFile(destIndex)
@ -78,7 +78,7 @@ func TestRepoIndexCmd(t *testing.T) {
require.NoError(t, linkOrCopy("testdata/testcharts/reqtest-0.1.0.tgz", filepath.Join(dir, "reqtest-0.1.0.tgz")))
require.NoError(t, linkOrCopy("testdata/testcharts/compressedchart-0.3.0.tgz", filepath.Join(dir, "compressedchart-0.3.0.tgz")))
c.ParseFlags([]string{"--merge", destIndex})
require.NoError(t, c.ParseFlags([]string{"--merge", destIndex}))
require.NoError(t, c.RunE(c, []string{dir}))
index, err = repo.LoadIndexFile(destIndex)
@ -95,7 +95,7 @@ func TestRepoIndexCmd(t *testing.T) {
// test that index.yaml gets generated on merge even when it doesn't exist
require.NoError(t, os.Remove(destIndex))
c.ParseFlags([]string{"--merge", destIndex})
require.NoError(t, c.ParseFlags([]string{"--merge", destIndex}))
require.NoError(t, c.RunE(c, []string{dir}))
index, err = repo.LoadIndexFile(destIndex)

@ -101,7 +101,7 @@ func TestUpdateCmdInvalid(t *testing.T) {
func TestUpdateCustomCacheCmd(t *testing.T) {
rootDir := t.TempDir()
cachePath := filepath.Join(rootDir, "updcustomcache")
os.Mkdir(cachePath, os.ModePerm)
require.NoError(t, os.Mkdir(cachePath, os.ModePerm))
ts := repotest.NewTempServer(
t,
@ -137,7 +137,7 @@ func TestUpdateCharts(t *testing.T) {
require.NoError(t, err)
b := bytes.NewBuffer(nil)
updateCharts([]*repo.ChartRepository{r}, b)
require.NoError(t, updateCharts([]*repo.ChartRepository{r}, b))
got := b.String()
assert.NotContains(t, got, "Unable to get an update", "Failed to get a repo: %q", got)

@ -85,7 +85,7 @@ func newRollbackCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
f := cmd.Flags()
f.BoolVar(&client.ForceReplace, "force-replace", false, "force resource updates by replacement")
f.BoolVar(&client.ForceReplace, "force", false, "deprecated")
f.MarkDeprecated("force", "use --force-replace instead")
_ = f.MarkDeprecated("force", "use --force-replace instead")
f.BoolVar(&client.ForceConflicts, "force-conflicts", false, "if set server-side apply will force changes against conflicts")
f.StringVar(&client.ServerSideApply, "server-side", "auto", "must be \"true\", \"false\" or \"auto\". Object updates run in the server instead of the client (\"auto\" defaults the value from the previous chart release's method)")
f.BoolVar(&client.DisableHooks, "no-hooks", false, "prevent hooks from running during rollback")

@ -176,7 +176,7 @@ func newRootCmdWithConfig(actionConfig *action.Configuration, out io.Writer, arg
// This call is required to gather configuration information prior to
// execution.
flags.ParseErrorsAllowlist.UnknownFlags = true
flags.Parse(args)
_ = flags.Parse(args)
logSetup(settings.Debug)

@ -211,7 +211,7 @@ func newTemplateCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
f.StringArrayVarP(&showFiles, "show-only", "s", []string{}, "only show manifests rendered from the given templates")
f.StringVar(&client.OutputDir, "output-dir", "", "writes the executed templates to files in output-dir instead of stdout")
f.BoolVar(&validate, "validate", false, "deprecated")
f.MarkDeprecated("validate", "use '--dry-run=server' instead")
_ = f.MarkDeprecated("validate", "use '--dry-run=server' instead")
f.BoolVar(&includeCrds, "include-crds", false, "include CRDs in the templated output")
f.BoolVar(&skipTests, "skip-tests", false, "skip tests from templated output")
f.BoolVar(&client.IsUpgrade, "is-upgrade", false, "set .Release.IsUpgrade instead of .Release.IsInstall")

@ -283,7 +283,7 @@ func newUpgradeCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
f.BoolVar(&client.HideSecret, "hide-secret", false, "hide Kubernetes Secrets when also using the --dry-run flag")
f.BoolVar(&client.ForceReplace, "force-replace", false, "force resource updates by replacement")
f.BoolVar(&client.ForceReplace, "force", false, "deprecated")
f.MarkDeprecated("force", "use --force-replace instead")
_ = f.MarkDeprecated("force", "use --force-replace instead")
f.BoolVar(&client.ForceConflicts, "force-conflicts", false, "if set server-side apply will force changes against conflicts")
f.StringVar(&client.ServerSideApply, "server-side", "auto", "must be \"true\", \"false\" or \"auto\". Object updates run in the server instead of the client (\"auto\" defaults the value from the previous chart release's method)")
f.BoolVar(&client.DisableHooks, "no-hooks", false, "disable pre/post upgrade hooks")
@ -296,7 +296,7 @@ func newUpgradeCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
f.BoolVar(&client.WaitForJobs, "wait-for-jobs", false, "if set and --wait enabled, will wait until all Jobs have been completed before marking the release as successful. It will wait for as long as --timeout")
f.BoolVar(&client.RollbackOnFailure, "rollback-on-failure", false, "if set, Helm will rollback the upgrade to previous success release upon failure. The --wait flag will be defaulted to \"watcher\" if --rollback-on-failure is set")
f.BoolVar(&client.RollbackOnFailure, "atomic", false, "deprecated")
f.MarkDeprecated("atomic", "use --rollback-on-failure instead")
_ = f.MarkDeprecated("atomic", "use --rollback-on-failure instead")
f.IntVar(&client.MaxHistory, "history-max", settings.MaxHistory, "limit the maximum number of revisions saved per release. Use 0 for no limit")
f.BoolVar(&client.CleanupOnFail, "cleanup-on-fail", false, "allow deletion of new resources created in this upgrade when upgrade fails")
f.BoolVar(&client.SubNotes, "render-subchart-notes", false, "if set, render subchart notes along with the parent")

@ -244,7 +244,7 @@ func TestUpgradeWithValue(t *testing.T) {
store := storageFixture()
store.Create(relMock(releaseName, 3, ch))
require.NoError(t, store.Create(relMock(releaseName, 3, ch)))
cmd := fmt.Sprintf("upgrade %s --set favoriteDrink=tea '%s'", releaseName, chartPath)
_, _, err := executeActionCommandC(store, cmd)
@ -266,7 +266,7 @@ func TestUpgradeWithStringValue(t *testing.T) {
store := storageFixture()
store.Create(relMock(releaseName, 3, ch))
require.NoError(t, store.Create(relMock(releaseName, 3, ch)))
cmd := fmt.Sprintf("upgrade %s --set-string favoriteDrink=coffee '%s'", releaseName, chartPath)
_, _, err := executeActionCommandC(store, cmd)
@ -288,7 +288,7 @@ func TestUpgradeInstallWithSubchartNotes(t *testing.T) {
store := storageFixture()
store.Create(relMock(releaseName, 1, ch))
require.NoError(t, store.Create(relMock(releaseName, 1, ch)))
cmd := fmt.Sprintf("upgrade %s -i --render-subchart-notes '%s'", releaseName, "testdata/testcharts/chart-with-subchart-notes")
_, _, err := executeActionCommandC(store, cmd)
@ -311,7 +311,7 @@ func TestUpgradeWithValuesFile(t *testing.T) {
store := storageFixture()
store.Create(relMock(releaseName, 3, ch))
require.NoError(t, store.Create(relMock(releaseName, 3, ch)))
cmd := fmt.Sprintf("upgrade %s --values testdata/testcharts/upgradetest/values.yaml '%s'", releaseName, chartPath)
_, _, err := executeActionCommandC(store, cmd)
@ -333,7 +333,7 @@ func TestUpgradeWithValuesFromStdin(t *testing.T) {
store := storageFixture()
store.Create(relMock(releaseName, 3, ch))
require.NoError(t, store.Create(relMock(releaseName, 3, ch)))
in, err := os.Open("testdata/testcharts/upgradetest/values.yaml")
require.NoError(t, err)

@ -355,8 +355,8 @@ func TestDownloadToCache(t *testing.T) {
// Case 1: Chart not in cache, download it.
t.Run("download and cache chart", func(t *testing.T) {
// Clear cache for this test
os.RemoveAll(contentCache)
os.MkdirAll(contentCache, 0o755)
require.NoError(t, os.RemoveAll(contentCache))
require.NoError(t, os.MkdirAll(contentCache, 0o755))
c.Cache = &DiskCache{Root: contentCache}
pth, v, err := c.DownloadToCache("test/signtest", "0.1.0")
@ -398,8 +398,8 @@ func TestDownloadToCache(t *testing.T) {
// Case 3: Download with verification
t.Run("download and verify", func(t *testing.T) {
// Clear cache
os.RemoveAll(contentCache)
os.MkdirAll(contentCache, 0o755)
require.NoError(t, os.RemoveAll(contentCache))
require.NoError(t, os.MkdirAll(contentCache, 0o755))
c.Cache = &DiskCache{Root: contentCache}
c.Verify = VerifyAlways
c.Keyring = "testdata/helm-test-key.pub"

@ -279,7 +279,7 @@ func TestDownloadTLSWithRedirect(t *testing.T) {
tlsSrv2 := httptest.NewUnstartedServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) {
rw.Header().Set("Content-Type", "text/plain")
rw.Write([]byte(srv2Resp))
_, _ = rw.Write([]byte(srv2Resp))
}))
tlsSrv2.TLS = tlsConf
@ -390,7 +390,7 @@ func TestHTTPGetterTarDownload(t *testing.T) {
defer f.Close()
b := make([]byte, 512)
f.Read(b)
_, _ = f.Read(b)
// Get the file size
FileStat, _ := f.Stat()
FileSize := strconv.FormatInt(FileStat.Size(), 10)
@ -400,8 +400,8 @@ func TestHTTPGetterTarDownload(t *testing.T) {
w.Header().Set("Content-Encoding", "gzip")
w.Header().Set("Content-Length", FileSize)
f.Seek(0, 0)
io.Copy(w, f)
_, _ = f.Seek(0, 0)
_, _ = io.Copy(w, f)
}))
defer srv.Close()

@ -47,7 +47,8 @@ func Empty() *Rules {
//
// Ignore all dotfiles in "templates/"
func (r *Rules) AddDefaults() {
r.parseRule(`templates/.?*`)
// The default rule is a hardcoded, known-valid pattern, so parsing cannot fail.
_ = r.parseRule(`templates/.?*`)
}
// ParseFile parses a helmignore file and returns the *Rules.

@ -1177,7 +1177,9 @@ func patchResourceClientSide(original runtime.Object, target *resource.Info, thr
return fmt.Errorf("cannot patch %q with kind %s: %w", target.Name, kind, err)
}
target.Refresh(obj, true)
if err := target.Refresh(obj, true); err != nil {
return fmt.Errorf("cannot refresh %q with kind %s: %w", target.Name, kind, err)
}
return nil
}

@ -1136,7 +1136,7 @@ type createPatchTestCase struct {
func (c createPatchTestCase) run(t *testing.T) {
scheme := runtime.NewScheme()
v1.AddToScheme(scheme)
require.NoError(t, v1.AddToScheme(scheme))
encoder := jsonserializer.NewSerializerWithOptions(
jsonserializer.DefaultMetaFactory, scheme, scheme, jsonserializer.SerializerOptions{
Yaml: false, Pretty: false, Strict: true,

@ -24,6 +24,7 @@ import (
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/cli-runtime/pkg/resource"
"k8s.io/client-go/kubernetes/scheme"
)
@ -61,11 +62,11 @@ func convertWithMapper(obj runtime.Object, mapping *meta.RESTMapping) runtime.Ob
func kubernetesNativeScheme() *runtime.Scheme {
k8sNativeSchemeOnce.Do(func() {
k8sNativeScheme = runtime.NewScheme()
scheme.AddToScheme(k8sNativeScheme)
utilruntime.Must(scheme.AddToScheme(k8sNativeScheme))
// API extensions are not in the above scheme set,
// and must thus be added separately.
apiextensionsv1beta1.AddToScheme(k8sNativeScheme)
apiextensionsv1.AddToScheme(k8sNativeScheme)
utilruntime.Must(apiextensionsv1beta1.AddToScheme(k8sNativeScheme))
utilruntime.Must(apiextensionsv1.AddToScheme(k8sNativeScheme))
})
return k8sNativeScheme
}

@ -59,7 +59,7 @@ func (rt *RetryingRoundTripper) roundTrip(req *http.Request, retry int, prevResp
var ke kubernetesError
r := bytes.NewReader(b)
err = json.NewDecoder(r).Decode(&ke)
r.Seek(0, io.SeekStart)
_, _ = r.Seek(0, io.SeekStart)
resp.Body = io.NopCloser(r)
if err != nil {
return resp, err

@ -250,7 +250,7 @@ func TestOCIPusher_Push_ChartOperations(t *testing.T) {
require.NoError(t, os.Chmod(tempChart, 0o000))
return tempChart, func() {
os.Chmod(tempChart, 0o644) // Restore permissions for cleanup
_ = os.Chmod(tempChart, 0o644) // Restore permissions for cleanup
}
},
href: "oci://localhost:5000/test",

@ -240,7 +240,7 @@ func initFakeRegistryTestServer() string {
switch r.URL.Path {
case "/v2/testrepo/image-index/manifests/0.1.0":
w.Header().Set("Content-Type", ocispec.MediaTypeImageIndex)
w.Write([]byte(`{
_, _ = w.Write([]byte(`{
"schemaVersion": 2,
"mediaType": "application/vnd.oci.image.index.v1+json",
"manifests": [
@ -286,7 +286,7 @@ func initFakeRegistryTestServer() string {
case "/v2/testrepo/image-index/manifests/sha256:2771e37a12b7bcb2902456ecf3f29bf9ee11ec348e66e8eb322d9780ad7fc2df":
w.Header().Set("Content-Type", ocispec.MediaTypeImageManifest)
w.Write([]byte(`{
_, _ = w.Write([]byte(`{
"schemaVersion": 2,
"mediaType": "application/vnd.oci.image.manifest.v1+json",
"config": {
@ -314,7 +314,7 @@ func initFakeRegistryTestServer() string {
case "/v2/testrepo/image-index/manifests/sha256:6b75187531c5e9b6a85c8946d5d82e4ef3801e051fbff338f382f3edfa60e3d2":
w.Header().Set("Content-Type", ocispec.MediaTypeImageManifest)
w.Write([]byte(`{
_, _ = w.Write([]byte(`{
"schemaVersion": 2,
"mediaType": "application/vnd.oci.image.manifest.v1+json",
"config": {
@ -336,7 +336,7 @@ func initFakeRegistryTestServer() string {
case "/v2/testrepo/image-index/manifests/sha256:7fbdc47de56b45d092f8f419e8b6183adf0159d00e05574c01787231b54fe28f":
w.Header().Set("Content-Type", ocispec.MediaTypeImageManifest)
w.Write([]byte(`{
_, _ = w.Write([]byte(`{
"schemaVersion": 2,
"config": {
"mediaType": "application/vnd.cncf.helm.config.v1+json",
@ -364,7 +364,7 @@ func initFakeRegistryTestServer() string {
case "/v2/testrepo/image-index/blobs/sha256:24de43e4a9f5ed9427479f27dd7bab9d158227abe593302a6f54d1e13a903ac3":
w.Header().Set("Content-Type", ConfigMediaType)
w.Write([]byte(`{
_, _ = w.Write([]byte(`{
"name":"signtest",
"version":"0.1.0",
"description":"A Helm chart for Kubernetes",
@ -375,20 +375,20 @@ func initFakeRegistryTestServer() string {
data, err := os.ReadFile("../downloader/testdata/signtest-0.1.0.tgz.prov")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
_, _ = w.Write([]byte(err.Error()))
} else {
w.Header().Set("Content-Type", ProvLayerMediaType)
w.Write(data)
_, _ = w.Write(data)
}
case "/v2/testrepo/image-index/blobs/sha256:e5ef611620fb97704d8751c16bab17fedb68883bfb0edc76f78a70e9173f9b55":
data, err := os.ReadFile("../downloader/testdata/signtest-0.1.0.tgz")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
_, _ = w.Write([]byte(err.Error()))
} else {
w.Header().Set("Content-Type", ChartLayerMediaType)
w.Write(data)
_, _ = w.Write(data)
}
default:

@ -109,13 +109,19 @@ func (r *ChartRepository) DownloadIndexFile() (string, error) {
fmt.Fprintln(&charts, name)
}
chartsFile := filepath.Join(r.CachePath, helmpath.CacheChartsFile(r.Config.Name))
os.MkdirAll(filepath.Dir(chartsFile), 0o755)
if err := os.MkdirAll(filepath.Dir(chartsFile), 0o755); err != nil {
return "", err
}
fileutil.AtomicWriteFile(chartsFile, bytes.NewReader([]byte(charts.String())), 0o644)
if err := fileutil.AtomicWriteFile(chartsFile, bytes.NewReader([]byte(charts.String())), 0o644); err != nil {
return "", err
}
// Create the index file in the cache directory
fname := filepath.Join(r.CachePath, helmpath.CacheIndexFile(r.Config.Name))
os.MkdirAll(filepath.Dir(fname), 0o755)
if err := os.MkdirAll(filepath.Dir(fname), 0o755); err != nil {
return "", err
}
return fname, fileutil.AtomicWriteFile(fname, bytes.NewReader(index), 0o644)
}

@ -132,7 +132,7 @@ func startLocalServerForTests(handler http.Handler) (*httptest.Server, error) {
return nil, err
}
handler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Write(fileBytes)
_, _ = w.Write(fileBytes)
})
}
@ -147,7 +147,7 @@ func startLocalTLSServerForTests(handler http.Handler) (*httptest.Server, error)
return nil, err
}
handler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Write(fileBytes)
_, _ = w.Write(fileBytes)
})
}

@ -257,7 +257,7 @@ func TestDownloadIndexFile(t *testing.T) {
require.NoError(t, err)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.RawPath == chartRepoURLPath+"/index.yaml" {
w.Write(fileBytes)
_, _ = w.Write(fileBytes)
}
})
srv, err := startLocalServerForTests(handler)
@ -444,7 +444,7 @@ func TestIndexWrite(t *testing.T) {
require.NoError(t, i.MustAdd(&chart.Metadata{APIVersion: "v2", Name: "clipper", Version: "0.1.0"}, "clipper-0.1.0.tgz", "http://example.com/charts", "sha256:1234567890"))
dir := t.TempDir()
testpath := filepath.Join(dir, "test")
i.WriteFile(testpath, 0o600)
require.NoError(t, i.WriteFile(testpath, 0o600))
got, err := os.ReadFile(testpath)
require.NoError(t, err)
@ -456,7 +456,7 @@ func TestIndexJSONWrite(t *testing.T) {
require.NoError(t, i.MustAdd(&chart.Metadata{APIVersion: "v2", Name: "clipper", Version: "0.1.0"}, "clipper-0.1.0.tgz", "http://example.com/charts", "sha256:1234567890"))
dir := t.TempDir()
testpath := filepath.Join(dir, "test")
i.WriteJSONFile(testpath, 0o600)
require.NoError(t, i.WriteJSONFile(testpath, 0o600))
got, err := os.ReadFile(testpath)
require.NoError(t, err)

@ -214,7 +214,9 @@ func (srv *OCIServer) RunWithReturn(t *testing.T, opts ...OCIServerOpt) *OCIServ
fn(cfg)
}
go srv.ListenAndServe()
go func() {
_ = srv.ListenAndServe()
}()
credentialsFile := filepath.Join(srv.Dir, "config.json")

@ -519,7 +519,7 @@ func (s *SQL) Create(key string, rel release.Releaser) error {
}
if _, err := transaction.Exec(insertQuery, args...); err != nil {
defer transaction.Rollback()
defer func() { _ = transaction.Rollback() }()
selectQuery, args, buildErr := s.statementBuilder.
Select(sqlReleaseTableKeyColumn).
@ -559,18 +559,18 @@ func (s *SQL) Create(key string, rel release.Releaser) error {
v,
).ToSql()
if err != nil {
defer transaction.Rollback()
defer func() { _ = transaction.Rollback() }()
s.Logger().Debug("failed to build insert query", slog.Any("error", err))
return err
}
if _, err := transaction.Exec(insertLabelsQuery, args...); err != nil {
defer transaction.Rollback()
defer func() { _ = transaction.Rollback() }()
s.Logger().Debug("failed to write Labels", slog.Any("error", err))
return err
}
}
defer transaction.Commit()
defer func() { _ = transaction.Commit() }()
return nil
}
@ -646,10 +646,10 @@ func (s *SQL) Delete(key string) (release.Releaser, error) {
release, err := decodeRelease(record.Body)
if err != nil {
s.Logger().Debug("failed to decode release", slog.String("key", key), slog.Any("error", err))
transaction.Rollback()
_ = transaction.Rollback()
return nil, err
}
defer transaction.Commit()
defer func() { _ = transaction.Commit() }()
deleteQuery, args, err := s.statementBuilder.
Delete(sqlReleaseTableName).

@ -448,7 +448,7 @@ func (t *parser) emptyVal() (bool, error) {
return true, nil
}
if !unicode.IsSpace(r) {
t.sc.UnreadRune()
_ = t.sc.UnreadRune()
return false, nil
}
}
@ -467,7 +467,7 @@ func (t *parser) valList() ([]any, error) {
}
if r != '{' {
t.sc.UnreadRune()
_ = t.sc.UnreadRune()
return []any{}, ErrNotList
}
@ -483,7 +483,7 @@ func (t *parser) valList() ([]any, error) {
case last == '}':
// If this is followed by ',', consume it.
if r, _, e := t.sc.ReadRune(); e == nil && r != ',' {
t.sc.UnreadRune()
_ = t.sc.UnreadRune()
}
v, e := t.reader(rs)
list = append(list, v)

Loading…
Cancel
Save