From 45966219b7982c7b3f1f32c2ec524844c7991272 Mon Sep 17 00:00:00 2001 From: thev1ndu Date: Wed, 5 Aug 2026 19:45:15 +0530 Subject: [PATCH] ci: enable errcheck linter and fix unchecked errors Signed-off-by: thev1ndu --- .golangci.yml | 1 + internal/chart/v3/fuzz_test.go | 4 ++-- internal/chart/v3/lint/rules/crds_test.go | 10 +++++----- internal/chart/v3/lint/rules/deprecations.go | 4 +++- internal/chart/v3/lint/rules/template_test.go | 4 ++-- internal/chart/v3/loader/load_test.go | 3 ++- internal/chart/v3/util/create_test.go | 2 +- internal/monocular/search.go | 4 +++- .../plugin/installer/oci_installer_test.go | 8 ++++---- internal/plugin/runtime_subprocess.go | 4 +++- internal/plugin/runtime_subprocess_test.go | 2 +- pkg/action/install.go | 2 +- pkg/action/release_testing.go | 4 +++- pkg/action/show.go | 4 +++- pkg/action/upgrade.go | 6 ++++-- pkg/chart/common/capabilities.go | 5 +++-- pkg/chart/common/util/jsonschema_test.go | 2 +- pkg/chart/loader/archive/archive.go | 4 +++- pkg/chart/v2/fuzz_test.go | 4 ++-- pkg/chart/v2/lint/rules/crds_test.go | 10 +++++----- pkg/chart/v2/lint/rules/deprecations.go | 4 +++- pkg/chart/v2/lint/rules/template_test.go | 4 ++-- pkg/chart/v2/loader/load_test.go | 3 ++- pkg/chart/v2/util/create_test.go | 2 +- pkg/chart/v2/util/expand_test.go | 3 ++- pkg/cli/environment_test.go | 2 +- pkg/cli/values/options_test.go | 2 +- pkg/cmd/completion_test.go | 4 ++-- pkg/cmd/create.go | 2 +- pkg/cmd/create_test.go | 2 +- pkg/cmd/dependency_build_test.go | 2 +- pkg/cmd/docs.go | 2 +- pkg/cmd/helpers_test.go | 2 +- pkg/cmd/install.go | 4 ++-- pkg/cmd/lint.go | 6 ++++-- pkg/cmd/list.go | 6 ++---- pkg/cmd/registry_login.go | 6 ++++-- pkg/cmd/release_testing_test.go | 2 +- pkg/cmd/repo_add.go | 2 +- pkg/cmd/repo_index.go | 4 +++- pkg/cmd/repo_index_test.go | 6 +++--- pkg/cmd/repo_update_test.go | 4 ++-- pkg/cmd/rollback.go | 2 +- pkg/cmd/root.go | 2 +- pkg/cmd/template.go | 2 +- pkg/cmd/upgrade.go | 4 ++-- pkg/cmd/upgrade_test.go | 10 +++++----- pkg/downloader/chart_downloader_test.go | 8 ++++---- pkg/getter/httpgetter_test.go | 8 ++++---- pkg/ignore/rules.go | 3 ++- pkg/kube/client.go | 4 +++- pkg/kube/client_test.go | 2 +- pkg/kube/converter.go | 7 ++++--- pkg/kubeenv/roundtripper.go | 2 +- pkg/pusher/ocipusher_test.go | 2 +- pkg/registry/registry_test.go | 18 +++++++++--------- pkg/repo/v1/chartrepo.go | 12 +++++++++--- pkg/repo/v1/chartrepo_test.go | 4 ++-- pkg/repo/v1/index_test.go | 6 +++--- pkg/repo/v1/repotest/server.go | 4 +++- pkg/storage/driver/sql.go | 12 ++++++------ pkg/strvals/parser.go | 6 +++--- 62 files changed, 158 insertions(+), 121 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 9daa85ad5..f807174ef 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -28,6 +28,7 @@ linters: - contextcheck - depguard - dupl + - errcheck - errorlint - exhaustive - fatcontext diff --git a/internal/chart/v3/fuzz_test.go b/internal/chart/v3/fuzz_test.go index 982c26489..ef34493a5 100644 --- a/internal/chart/v3/fuzz_test.go +++ b/internal/chart/v3/fuzz_test.go @@ -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() }) } diff --git a/internal/chart/v3/lint/rules/crds_test.go b/internal/chart/v3/lint/rules/crds_test.go index 9009c1801..f118b66cd 100644 --- a/internal/chart/v3/lint/rules/crds_test.go +++ b/internal/chart/v3/lint/rules/crds_test.go @@ -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) diff --git a/internal/chart/v3/lint/rules/deprecations.go b/internal/chart/v3/lint/rules/deprecations.go index 85dddd114..1f235a02b 100644 --- a/internal/chart/v3/lint/rules/deprecations.go +++ b/internal/chart/v3/lint/rules/deprecations.go @@ -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) diff --git a/internal/chart/v3/lint/rules/template_test.go b/internal/chart/v3/lint/rules/template_test.go index 4a1e15f55..bf018137b 100644 --- a/internal/chart/v3/lint/rules/template_test.go +++ b/internal/chart/v3/lint/rules/template_test.go @@ -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) diff --git a/internal/chart/v3/loader/load_test.go b/internal/chart/v3/loader/load_test.go index dd5fdc8db..8a4850c2c 100644 --- a/internal/chart/v3/loader/load_test.go +++ b/internal/chart/v3/loader/load_test.go @@ -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()) } diff --git a/internal/chart/v3/util/create_test.go b/internal/chart/v3/util/create_test.go index ddbbf6216..cffb118c5 100644 --- a/internal/chart/v3/util/create_test.go +++ b/internal/chart/v3/util/create_test.go @@ -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 diff --git a/internal/monocular/search.go b/internal/monocular/search.go index 29cc7f1a4..986701a3f 100644 --- a/internal/monocular/search.go +++ b/internal/monocular/search.go @@ -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 } diff --git a/internal/plugin/installer/oci_installer_test.go b/internal/plugin/installer/oci_installer_test.go index ce381d12c..0b1e37775 100644 --- a/internal/plugin/installer/oci_installer_test.go +++ b/internal/plugin/installer/oci_installer_test.go @@ -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) diff --git a/internal/plugin/runtime_subprocess.go b/internal/plugin/runtime_subprocess.go index 2dbe220d9..9a3cdfe0a 100644 --- a/internal/plugin/runtime_subprocess.go +++ b/internal/plugin/runtime_subprocess.go @@ -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{} diff --git a/internal/plugin/runtime_subprocess_test.go b/internal/plugin/runtime_subprocess_test.go index c04127e0d..31487cb70 100644 --- a/internal/plugin/runtime_subprocess_test.go +++ b/internal/plugin/runtime_subprocess_test.go @@ -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, diff --git a/pkg/action/install.go b/pkg/action/install.go index 605c423bc..b1d75db5c 100644 --- a/pkg/action/install.go +++ b/pkg/action/install.go @@ -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 } diff --git a/pkg/action/release_testing.go b/pkg/action/release_testing.go index 6edb644c1..6e775f71d 100644 --- a/pkg/action/release_testing.go +++ b/pkg/action/release_testing.go @@ -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 } diff --git a/pkg/action/show.go b/pkg/action/show.go index 4195d69a5..ba9213fa1 100644 --- a/pkg/action/show.go +++ b/pkg/action/show.go @@ -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 { diff --git a/pkg/action/upgrade.go b/pkg/action/upgrade.go index 7f66ceefb..856f5041e 100644 --- a/pkg/action/upgrade.go +++ b/pkg/action/upgrade.go @@ -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) diff --git a/pkg/chart/common/capabilities.go b/pkg/chart/common/capabilities.go index a9374a86f..5587c6b2b 100644 --- a/pkg/chart/common/capabilities.go +++ b/pkg/chart/common/capabilities.go @@ -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)) diff --git a/pkg/chart/common/util/jsonschema_test.go b/pkg/chart/common/util/jsonschema_test.go index 90fdc9b11..c99b32921 100644 --- a/pkg/chart/common/util/jsonschema_test.go +++ b/pkg/chart/common/util/jsonschema_test.go @@ -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() diff --git a/pkg/chart/loader/archive/archive.go b/pkg/chart/loader/archive/archive.go index a35c0152d..fa2639020 100644 --- a/pkg/chart/loader/archive/archive.go +++ b/pkg/chart/loader/archive/archive.go @@ -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) diff --git a/pkg/chart/v2/fuzz_test.go b/pkg/chart/v2/fuzz_test.go index a897ef7b9..092b69d01 100644 --- a/pkg/chart/v2/fuzz_test.go +++ b/pkg/chart/v2/fuzz_test.go @@ -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() }) } diff --git a/pkg/chart/v2/lint/rules/crds_test.go b/pkg/chart/v2/lint/rules/crds_test.go index d0790692f..31055f4a5 100644 --- a/pkg/chart/v2/lint/rules/crds_test.go +++ b/pkg/chart/v2/lint/rules/crds_test.go @@ -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) diff --git a/pkg/chart/v2/lint/rules/deprecations.go b/pkg/chart/v2/lint/rules/deprecations.go index 2ed682891..5579ed39a 100644 --- a/pkg/chart/v2/lint/rules/deprecations.go +++ b/pkg/chart/v2/lint/rules/deprecations.go @@ -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) diff --git a/pkg/chart/v2/lint/rules/template_test.go b/pkg/chart/v2/lint/rules/template_test.go index 3f350557b..c76ee8470 100644 --- a/pkg/chart/v2/lint/rules/template_test.go +++ b/pkg/chart/v2/lint/rules/template_test.go @@ -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( diff --git a/pkg/chart/v2/loader/load_test.go b/pkg/chart/v2/loader/load_test.go index 8bf254321..506915fca 100644 --- a/pkg/chart/v2/loader/load_test.go +++ b/pkg/chart/v2/loader/load_test.go @@ -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()) } diff --git a/pkg/chart/v2/util/create_test.go b/pkg/chart/v2/util/create_test.go index 69ba1336d..90a84cbb7 100644 --- a/pkg/chart/v2/util/create_test.go +++ b/pkg/chart/v2/util/create_test.go @@ -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 diff --git a/pkg/chart/v2/util/expand_test.go b/pkg/chart/v2/util/expand_test.go index bc8cc7855..a69b4bdf1 100644 --- a/pkg/chart/v2/util/expand_test.go +++ b/pkg/chart/v2/util/expand_test.go @@ -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 { diff --git a/pkg/cli/environment_test.go b/pkg/cli/environment_test.go index fc71038f8..4a14bebab 100644 --- a/pkg/cli/environment_test.go +++ b/pkg/cli/environment_test.go @@ -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") diff --git a/pkg/cli/values/options_test.go b/pkg/cli/values/options_test.go index 6debb693e..d85093a63 100644 --- a/pkg/cli/values/options_test.go +++ b/pkg/cli/values/options_test.go @@ -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 diff --git a/pkg/cmd/completion_test.go b/pkg/cmd/completion_test.go index 296ae457e..88c1352a7 100644 --- a/pkg/cmd/completion_test.go +++ b/pkg/cmd/completion_test.go @@ -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) diff --git a/pkg/cmd/create.go b/pkg/cmd/create.go index b38ce6a12..cde7f377d 100644 --- a/pkg/cmd/create.go +++ b/pkg/cmd/create.go @@ -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 diff --git a/pkg/cmd/create_test.go b/pkg/cmd/create_test.go index 6f25d4c63..86b0bd2df 100644 --- a/pkg/cmd/create_test.go +++ b/pkg/cmd/create_test.go @@ -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" { diff --git a/pkg/cmd/dependency_build_test.go b/pkg/cmd/dependency_build_test.go index 1680c23a1..df22f37b7 100644 --- a/pkg/cmd/dependency_build_test.go +++ b/pkg/cmd/dependency_build_test.go @@ -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) diff --git a/pkg/cmd/docs.go b/pkg/cmd/docs.go index 6463170b9..832d5f12e 100644 --- a/pkg/cmd/docs.go +++ b/pkg/cmd/docs.go @@ -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 }) diff --git a/pkg/cmd/helpers_test.go b/pkg/cmd/helpers_test.go index 611d1a54c..f856536f8 100644 --- a/pkg/cmd/helpers_test.go +++ b/pkg/cmd/helpers_test.go @@ -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) diff --git a/pkg/cmd/install.go b/pkg/cmd/install.go index b6cee5843..d278defb7 100644 --- a/pkg/cmd/install.go +++ b/pkg/cmd/install.go @@ -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") diff --git a/pkg/cmd/lint.go b/pkg/cmd/lint.go index 1b5c3b212..769fec764 100644 --- a/pkg/cmd/lint.go +++ b/pkg/cmd/lint.go @@ -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 + } } } diff --git a/pkg/cmd/list.go b/pkg/cmd/list.go index 54becddca..eaf93f84b 100644 --- a/pkg/cmd/list.go +++ b/pkg/cmd/list.go @@ -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) diff --git a/pkg/cmd/registry_login.go b/pkg/cmd/registry_login.go index bffc56445..cf30431df 100644 --- a/pkg/cmd/registry_login.go +++ b/pkg/cmd/registry_login.go @@ -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) diff --git a/pkg/cmd/release_testing_test.go b/pkg/cmd/release_testing_test.go index a39816843..1416327d7 100644 --- a/pkg/cmd/release_testing_test.go +++ b/pkg/cmd/release_testing_test.go @@ -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{ diff --git a/pkg/cmd/repo_add.go b/pkg/cmd/repo_add.go index a7a02ef75..6f421ae7a 100644 --- a/pkg/cmd/repo_add.go +++ b/pkg/cmd/repo_add.go @@ -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 diff --git a/pkg/cmd/repo_index.go b/pkg/cmd/repo_index.go index ece0ce811..0bfda526d 100644 --- a/pkg/cmd/repo_index.go +++ b/pkg/cmd/repo_index.go @@ -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 { diff --git a/pkg/cmd/repo_index_test.go b/pkg/cmd/repo_index_test.go index 67984f3b7..cd84400c1 100644 --- a/pkg/cmd/repo_index_test.go +++ b/pkg/cmd/repo_index_test.go @@ -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) diff --git a/pkg/cmd/repo_update_test.go b/pkg/cmd/repo_update_test.go index e8d7ad64a..d74d0da53 100644 --- a/pkg/cmd/repo_update_test.go +++ b/pkg/cmd/repo_update_test.go @@ -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) diff --git a/pkg/cmd/rollback.go b/pkg/cmd/rollback.go index b716dae10..a3bbe7025 100644 --- a/pkg/cmd/rollback.go +++ b/pkg/cmd/rollback.go @@ -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") diff --git a/pkg/cmd/root.go b/pkg/cmd/root.go index dbedca026..32b021bdb 100644 --- a/pkg/cmd/root.go +++ b/pkg/cmd/root.go @@ -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) diff --git a/pkg/cmd/template.go b/pkg/cmd/template.go index 29839b871..103bf7c40 100644 --- a/pkg/cmd/template.go +++ b/pkg/cmd/template.go @@ -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") diff --git a/pkg/cmd/upgrade.go b/pkg/cmd/upgrade.go index 688842141..4e61db3c4 100644 --- a/pkg/cmd/upgrade.go +++ b/pkg/cmd/upgrade.go @@ -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") diff --git a/pkg/cmd/upgrade_test.go b/pkg/cmd/upgrade_test.go index 5aba7b11b..d53b20951 100644 --- a/pkg/cmd/upgrade_test.go +++ b/pkg/cmd/upgrade_test.go @@ -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) diff --git a/pkg/downloader/chart_downloader_test.go b/pkg/downloader/chart_downloader_test.go index 92d4f024d..59b160c1c 100644 --- a/pkg/downloader/chart_downloader_test.go +++ b/pkg/downloader/chart_downloader_test.go @@ -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" diff --git a/pkg/getter/httpgetter_test.go b/pkg/getter/httpgetter_test.go index aebb6f11c..90ddfb6db 100644 --- a/pkg/getter/httpgetter_test.go +++ b/pkg/getter/httpgetter_test.go @@ -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() diff --git a/pkg/ignore/rules.go b/pkg/ignore/rules.go index a8160da2a..f8f48fd0f 100644 --- a/pkg/ignore/rules.go +++ b/pkg/ignore/rules.go @@ -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. diff --git a/pkg/kube/client.go b/pkg/kube/client.go index ba881c560..ccc91e73f 100644 --- a/pkg/kube/client.go +++ b/pkg/kube/client.go @@ -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 } diff --git a/pkg/kube/client_test.go b/pkg/kube/client_test.go index 86574a3e5..e7f0b5f6d 100644 --- a/pkg/kube/client_test.go +++ b/pkg/kube/client_test.go @@ -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, diff --git a/pkg/kube/converter.go b/pkg/kube/converter.go index 7bdc143ac..8e968836c 100644 --- a/pkg/kube/converter.go +++ b/pkg/kube/converter.go @@ -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 } diff --git a/pkg/kubeenv/roundtripper.go b/pkg/kubeenv/roundtripper.go index e00f93984..bc8495974 100644 --- a/pkg/kubeenv/roundtripper.go +++ b/pkg/kubeenv/roundtripper.go @@ -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 diff --git a/pkg/pusher/ocipusher_test.go b/pkg/pusher/ocipusher_test.go index b63077293..a02a323f3 100644 --- a/pkg/pusher/ocipusher_test.go +++ b/pkg/pusher/ocipusher_test.go @@ -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", diff --git a/pkg/registry/registry_test.go b/pkg/registry/registry_test.go index 40ebe9687..7fbb26edc 100644 --- a/pkg/registry/registry_test.go +++ b/pkg/registry/registry_test.go @@ -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: diff --git a/pkg/repo/v1/chartrepo.go b/pkg/repo/v1/chartrepo.go index 42ed52f75..0b1505597 100644 --- a/pkg/repo/v1/chartrepo.go +++ b/pkg/repo/v1/chartrepo.go @@ -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) } diff --git a/pkg/repo/v1/chartrepo_test.go b/pkg/repo/v1/chartrepo_test.go index f0e5839ac..c7d8f9e56 100644 --- a/pkg/repo/v1/chartrepo_test.go +++ b/pkg/repo/v1/chartrepo_test.go @@ -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) }) } diff --git a/pkg/repo/v1/index_test.go b/pkg/repo/v1/index_test.go index 9b46065a8..67498f5d7 100644 --- a/pkg/repo/v1/index_test.go +++ b/pkg/repo/v1/index_test.go @@ -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) diff --git a/pkg/repo/v1/repotest/server.go b/pkg/repo/v1/repotest/server.go index 06cdc9172..4177fcfd0 100644 --- a/pkg/repo/v1/repotest/server.go +++ b/pkg/repo/v1/repotest/server.go @@ -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") diff --git a/pkg/storage/driver/sql.go b/pkg/storage/driver/sql.go index db076da98..e057570b0 100644 --- a/pkg/storage/driver/sql.go +++ b/pkg/storage/driver/sql.go @@ -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). diff --git a/pkg/strvals/parser.go b/pkg/strvals/parser.go index be3b1e71b..dff424f33 100644 --- a/pkg/strvals/parser.go +++ b/pkg/strvals/parser.go @@ -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)