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 - contextcheck
- depguard - depguard
- dupl - dupl
- errcheck
- errorlint - errorlint
- exhaustive - exhaustive
- fatcontext - fatcontext

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

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

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

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

@ -274,7 +274,8 @@ icon: https://example.com/64x64.png
w.Close() w.Close()
var text bytes.Buffer 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()) 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") dir := filepath.Join(tdir, "foo")
tplname := filepath.Join(dir, "templates", "hpa.yaml") tplname := filepath.Join(dir, "templates", "hpa.yaml")
writeFile(tplname, []byte("FOO")) require.NoError(t, writeFile(tplname, []byte("FOO")))
// Now re-run the create // Now re-run the create
Stderr = &errlog Stderr = &errlog

@ -142,7 +142,9 @@ func (c *Client) SearchWithContext(ctx context.Context, term string) ([]SearchRe
result := &searchResponse{} 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 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("Docker-Distribution-API-Version", "registry/2.0")
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK) 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): case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/manifests/") && strings.Contains(r.URL.Path, pluginName):
// Return manifest // Return manifest
w.Header().Set("Content-Type", ocispec.MediaTypeImageManifest) w.Header().Set("Content-Type", ocispec.MediaTypeImageManifest)
w.Header().Set("Docker-Content-Digest", manifestDigest) w.Header().Set("Docker-Content-Digest", manifestDigest)
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
w.Write(manifestData) _, _ = w.Write(manifestData)
case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/blobs/"+layerDigest): case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/blobs/"+layerDigest):
// Return layer data // Return layer data
w.Header().Set("Content-Type", "application/vnd.oci.image.layer.v1.tar") w.Header().Set("Content-Type", "application/vnd.oci.image.layer.v1.tar")
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
w.Write(pluginData) _, _ = w.Write(pluginData)
case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/blobs/"+configDigest): case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/blobs/"+configDigest):
// Return config data // Return config data
w.Header().Set("Content-Type", "application/vnd.oci.empty.v1+json") w.Header().Set("Content-Type", "application/vnd.oci.empty.v1+json")
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
w.Write(configData) _, _ = w.Write(configData)
default: default:
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)

@ -255,7 +255,9 @@ func (r *SubprocessPluginRuntime) runPostrenderer(ctx context.Context, input *In
go func() { go func() {
defer stdin.Close() 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{} postRendered := &bytes.Buffer{}

@ -56,7 +56,7 @@ func mockSubprocessCLIPluginErrorExit(t *testing.T, pluginName string, exitCode
data, err := yaml.Marshal(md) data, err := yaml.Marshal(md)
require.NoError(t, err) 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{ return &SubprocessPluginRuntime{
metadata: md, 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) 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 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) shutdown, err := r.cfg.execHookWithDelayedShutdown(rel, release.HookTest, kube.StatusWatcherStrategy, r.WaitOptions, r.Timeout, serverSideApply)
if err != nil { if err != nil {
rel.Hooks = append(skippedHooks, rel.Hooks...) 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 return reli, shutdown, err
} }

@ -107,7 +107,9 @@ func (s *Show) Run(chartpath string) (string, error) {
if err != nil { if err != nil {
return "", fmt.Errorf("error parsing jsonpath %s: %w", s.JSONPathTemplate, err) 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 { } else {
for _, f := range s.chart.Raw { for _, f := range s.chart.Raw {
if f.Name == chartutil.ValuesfileName { 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) 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 { if err != nil {
return err return err
} }
current.Append(r) current.Append(r)
return nil return nil
}) }); err != nil {
return nil, err
}
if isDryRun(u.DryRunStrategy) { if isDryRun(u.DryRunStrategy) {
u.cfg.Logger().Debug("dry run for release", "name", upgradedRelease.Name) 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" apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
k8sversion "k8s.io/apimachinery/pkg/util/version" k8sversion "k8s.io/apimachinery/pkg/util/version"
helmversion "helm.sh/helm/v4/internal/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 // 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 // supported in the default version set. This has caused problems with `helm
// template` in the past, so let's be safe // template` in the past, so let's be safe
apiextensionsv1beta1.AddToScheme(scheme.Scheme) utilruntime.Must(apiextensionsv1beta1.AddToScheme(scheme.Scheme))
apiextensionsv1.AddToScheme(scheme.Scheme) utilruntime.Must(apiextensionsv1.AddToScheme(scheme.Scheme))
groups := scheme.Scheme.PrioritizedVersionsAllGroups() groups := scheme.Scheme.PrioritizedVersionsAllGroups()
vs := make(VersionSet, 0, len(groups)) 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) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK) 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() 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 // of this is invoking `helm template values.yaml mychart` which would otherwise produce a confusing error
// if we didn't check for this. // if we didn't check for this.
func EnsureArchive(name string, raw *os.File) error { 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. // Check the file format to give us a chance to provide the user with more actionable feedback.
buffer := make([]byte, 512) buffer := make([]byte, 512)

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

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

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

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

@ -316,7 +316,8 @@ icon: https://example.com/64x64.png
w.Close() w.Close()
var text bytes.Buffer 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()) 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") dir := filepath.Join(tdir, "foo")
tplname := filepath.Join(dir, "templates", "hpa.yaml") tplname := filepath.Join(dir, "templates", "hpa.yaml")
writeFile(tplname, []byte("FOO")) require.NoError(t, writeFile(tplname, []byte("FOO")))
// Now re-run the create // Now re-run the create
Stderr = &errlog Stderr = &errlog

@ -55,7 +55,8 @@ func makeTestChartArchive(t *testing.T, chartName, sourceDir string) *bytes.Buff
data, err := fs.ReadFile(dir, relPath) data, err := fs.ReadFile(dir, relPath)
require.NoError(t, err) 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 { 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 := New()
settings.AddFlags(flags) 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.debug, settings.Debug, "debug")
assert.Equal(t, tt.ns, settings.Namespace(), "namespace") assert.Equal(t, tt.ns, settings.Namespace(), "namespace")

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

@ -32,7 +32,7 @@ import (
func checkFileCompletion(t *testing.T, cmdName string, shouldBePerformed bool) { func checkFileCompletion(t *testing.T, cmdName string, shouldBePerformed bool) {
t.Helper() t.Helper()
storage := storageFixture() storage := storageFixture()
storage.Create(&release.Release{ require.NoError(t, storage.Create(&release.Release{
Name: "myrelease", Name: "myrelease",
Info: &release.Info{Status: common.StatusDeployed}, Info: &release.Info{Status: common.StatusDeployed},
Chart: &chart.Chart{ Chart: &chart.Chart{
@ -42,7 +42,7 @@ func checkFileCompletion(t *testing.T, cmdName string, shouldBePerformed bool) {
}, },
}, },
Version: 1, Version: 1,
}) }))
testcmd := fmt.Sprintf("__complete %s ''", cmdName) testcmd := fmt.Sprintf("__complete %s ''", cmdName)
_, out, err := executeActionCommandC(storage, testcmd) _, 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)") cmd.Flags().StringVar(&o.chartAPIVersion, "chart-api-version", chart.APIVersionV2, "chart API version to use (v2 or v3)")
if !gates.ChartV3.IsEnabled() { if !gates.ChartV3.IsEnabled() {
cmd.Flags().MarkHidden("chart-api-version") _ = cmd.Flags().MarkHidden("chart-api-version")
} }
return cmd return cmd

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

@ -38,7 +38,7 @@ func TestDependencyBuildCmd(t *testing.T) {
defer srv.Stop() defer srv.Stop()
rootDir := srv.Root() rootDir := srv.Root()
srv.LinkIndices() require.NoError(t, srv.LinkIndices())
ociSrv, err := repotest.NewOCIServer(t, srv.Root()) ociSrv, err := repotest.NewOCIServer(t, srv.Root())
require.NoError(t, err) 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.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") 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 return []string{"bash", "man", "markdown"}, cobra.ShellCompDirectiveNoFileComp
}) })

@ -278,7 +278,7 @@ func TestCmdGetDryRunFlagStrategy(t *testing.T) {
Use: "helm", Use: "helm",
} }
addDryRunFlag(cmd) 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) { t.Run(name, func(t *testing.T) {
dryRunStrategy, err := cmdGetDryRunFlagStrategy(cmd, tc.IsTemplate) 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.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-replace", false, "force resource updates by replacement")
f.BoolVar(&client.ForceReplace, "force", false, "deprecated") 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.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.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") 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.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, "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.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.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.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") 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 { if client.WithSubcharts {
for _, p := range paths { 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 != nil {
if info.Name() == "Chart.yaml" { if info.Name() == "Chart.yaml" {
paths = append(paths, filepath.Dir(path)) paths = append(paths, filepath.Dir(path))
@ -75,7 +75,9 @@ func newLintCmd(out io.Writer) *cobra.Command {
} }
} }
return nil return nil
}) }); err != nil {
return err
}
} }
} }

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

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

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

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

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

@ -62,7 +62,7 @@ func TestRepoIndexCmd(t *testing.T) {
// Test with `--json` // Test with `--json`
c.ParseFlags([]string{"--json", "true"}) require.NoError(t, c.ParseFlags([]string{"--json", "true"}))
require.NoError(t, c.RunE(c, []string{dir})) require.NoError(t, c.RunE(c, []string{dir}))
b, err = os.ReadFile(destIndex) 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/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"))) 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})) require.NoError(t, c.RunE(c, []string{dir}))
index, err = repo.LoadIndexFile(destIndex) 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 // test that index.yaml gets generated on merge even when it doesn't exist
require.NoError(t, os.Remove(destIndex)) 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})) require.NoError(t, c.RunE(c, []string{dir}))
index, err = repo.LoadIndexFile(destIndex) index, err = repo.LoadIndexFile(destIndex)

@ -101,7 +101,7 @@ func TestUpdateCmdInvalid(t *testing.T) {
func TestUpdateCustomCacheCmd(t *testing.T) { func TestUpdateCustomCacheCmd(t *testing.T) {
rootDir := t.TempDir() rootDir := t.TempDir()
cachePath := filepath.Join(rootDir, "updcustomcache") cachePath := filepath.Join(rootDir, "updcustomcache")
os.Mkdir(cachePath, os.ModePerm) require.NoError(t, os.Mkdir(cachePath, os.ModePerm))
ts := repotest.NewTempServer( ts := repotest.NewTempServer(
t, t,
@ -137,7 +137,7 @@ func TestUpdateCharts(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
b := bytes.NewBuffer(nil) b := bytes.NewBuffer(nil)
updateCharts([]*repo.ChartRepository{r}, b) require.NoError(t, updateCharts([]*repo.ChartRepository{r}, b))
got := b.String() got := b.String()
assert.NotContains(t, got, "Unable to get an update", "Failed to get a repo: %q", got) 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 := cmd.Flags()
f.BoolVar(&client.ForceReplace, "force-replace", false, "force resource updates by replacement") f.BoolVar(&client.ForceReplace, "force-replace", false, "force resource updates by replacement")
f.BoolVar(&client.ForceReplace, "force", false, "deprecated") 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.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.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") 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 // This call is required to gather configuration information prior to
// execution. // execution.
flags.ParseErrorsAllowlist.UnknownFlags = true flags.ParseErrorsAllowlist.UnknownFlags = true
flags.Parse(args) _ = flags.Parse(args)
logSetup(settings.Debug) 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.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.StringVar(&client.OutputDir, "output-dir", "", "writes the executed templates to files in output-dir instead of stdout")
f.BoolVar(&validate, "validate", false, "deprecated") 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(&includeCrds, "include-crds", false, "include CRDs in the templated output")
f.BoolVar(&skipTests, "skip-tests", false, "skip tests from 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") 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.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-replace", false, "force resource updates by replacement")
f.BoolVar(&client.ForceReplace, "force", false, "deprecated") 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.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.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") 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.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, "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.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.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.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") 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 := 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) cmd := fmt.Sprintf("upgrade %s --set favoriteDrink=tea '%s'", releaseName, chartPath)
_, _, err := executeActionCommandC(store, cmd) _, _, err := executeActionCommandC(store, cmd)
@ -266,7 +266,7 @@ func TestUpgradeWithStringValue(t *testing.T) {
store := storageFixture() 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) cmd := fmt.Sprintf("upgrade %s --set-string favoriteDrink=coffee '%s'", releaseName, chartPath)
_, _, err := executeActionCommandC(store, cmd) _, _, err := executeActionCommandC(store, cmd)
@ -288,7 +288,7 @@ func TestUpgradeInstallWithSubchartNotes(t *testing.T) {
store := storageFixture() 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") cmd := fmt.Sprintf("upgrade %s -i --render-subchart-notes '%s'", releaseName, "testdata/testcharts/chart-with-subchart-notes")
_, _, err := executeActionCommandC(store, cmd) _, _, err := executeActionCommandC(store, cmd)
@ -311,7 +311,7 @@ func TestUpgradeWithValuesFile(t *testing.T) {
store := storageFixture() 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) cmd := fmt.Sprintf("upgrade %s --values testdata/testcharts/upgradetest/values.yaml '%s'", releaseName, chartPath)
_, _, err := executeActionCommandC(store, cmd) _, _, err := executeActionCommandC(store, cmd)
@ -333,7 +333,7 @@ func TestUpgradeWithValuesFromStdin(t *testing.T) {
store := storageFixture() 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") in, err := os.Open("testdata/testcharts/upgradetest/values.yaml")
require.NoError(t, err) require.NoError(t, err)

@ -355,8 +355,8 @@ func TestDownloadToCache(t *testing.T) {
// Case 1: Chart not in cache, download it. // Case 1: Chart not in cache, download it.
t.Run("download and cache chart", func(t *testing.T) { t.Run("download and cache chart", func(t *testing.T) {
// Clear cache for this test // Clear cache for this test
os.RemoveAll(contentCache) require.NoError(t, os.RemoveAll(contentCache))
os.MkdirAll(contentCache, 0o755) require.NoError(t, os.MkdirAll(contentCache, 0o755))
c.Cache = &DiskCache{Root: contentCache} c.Cache = &DiskCache{Root: contentCache}
pth, v, err := c.DownloadToCache("test/signtest", "0.1.0") pth, v, err := c.DownloadToCache("test/signtest", "0.1.0")
@ -398,8 +398,8 @@ func TestDownloadToCache(t *testing.T) {
// Case 3: Download with verification // Case 3: Download with verification
t.Run("download and verify", func(t *testing.T) { t.Run("download and verify", func(t *testing.T) {
// Clear cache // Clear cache
os.RemoveAll(contentCache) require.NoError(t, os.RemoveAll(contentCache))
os.MkdirAll(contentCache, 0o755) require.NoError(t, os.MkdirAll(contentCache, 0o755))
c.Cache = &DiskCache{Root: contentCache} c.Cache = &DiskCache{Root: contentCache}
c.Verify = VerifyAlways c.Verify = VerifyAlways
c.Keyring = "testdata/helm-test-key.pub" 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) { tlsSrv2 := httptest.NewUnstartedServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) {
rw.Header().Set("Content-Type", "text/plain") rw.Header().Set("Content-Type", "text/plain")
rw.Write([]byte(srv2Resp)) _, _ = rw.Write([]byte(srv2Resp))
})) }))
tlsSrv2.TLS = tlsConf tlsSrv2.TLS = tlsConf
@ -390,7 +390,7 @@ func TestHTTPGetterTarDownload(t *testing.T) {
defer f.Close() defer f.Close()
b := make([]byte, 512) b := make([]byte, 512)
f.Read(b) _, _ = f.Read(b)
// Get the file size // Get the file size
FileStat, _ := f.Stat() FileStat, _ := f.Stat()
FileSize := strconv.FormatInt(FileStat.Size(), 10) 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-Encoding", "gzip")
w.Header().Set("Content-Length", FileSize) w.Header().Set("Content-Length", FileSize)
f.Seek(0, 0) _, _ = f.Seek(0, 0)
io.Copy(w, f) _, _ = io.Copy(w, f)
})) }))
defer srv.Close() defer srv.Close()

@ -47,7 +47,8 @@ func Empty() *Rules {
// //
// Ignore all dotfiles in "templates/" // Ignore all dotfiles in "templates/"
func (r *Rules) AddDefaults() { 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. // 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) 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 return nil
} }

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

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

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

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

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

@ -109,13 +109,19 @@ func (r *ChartRepository) DownloadIndexFile() (string, error) {
fmt.Fprintln(&charts, name) fmt.Fprintln(&charts, name)
} }
chartsFile := filepath.Join(r.CachePath, helmpath.CacheChartsFile(r.Config.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 // Create the index file in the cache directory
fname := filepath.Join(r.CachePath, helmpath.CacheIndexFile(r.Config.Name)) 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) return fname, fileutil.AtomicWriteFile(fname, bytes.NewReader(index), 0o644)
} }

@ -132,7 +132,7 @@ func startLocalServerForTests(handler http.Handler) (*httptest.Server, error) {
return nil, err return nil, err
} }
handler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { 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 return nil, err
} }
handler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { 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) require.NoError(t, err)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.RawPath == chartRepoURLPath+"/index.yaml" { if r.URL.RawPath == chartRepoURLPath+"/index.yaml" {
w.Write(fileBytes) _, _ = w.Write(fileBytes)
} }
}) })
srv, err := startLocalServerForTests(handler) 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")) 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() dir := t.TempDir()
testpath := filepath.Join(dir, "test") testpath := filepath.Join(dir, "test")
i.WriteFile(testpath, 0o600) require.NoError(t, i.WriteFile(testpath, 0o600))
got, err := os.ReadFile(testpath) got, err := os.ReadFile(testpath)
require.NoError(t, err) 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")) 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() dir := t.TempDir()
testpath := filepath.Join(dir, "test") testpath := filepath.Join(dir, "test")
i.WriteJSONFile(testpath, 0o600) require.NoError(t, i.WriteJSONFile(testpath, 0o600))
got, err := os.ReadFile(testpath) got, err := os.ReadFile(testpath)
require.NoError(t, err) require.NoError(t, err)

@ -214,7 +214,9 @@ func (srv *OCIServer) RunWithReturn(t *testing.T, opts ...OCIServerOpt) *OCIServ
fn(cfg) fn(cfg)
} }
go srv.ListenAndServe() go func() {
_ = srv.ListenAndServe()
}()
credentialsFile := filepath.Join(srv.Dir, "config.json") 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 { if _, err := transaction.Exec(insertQuery, args...); err != nil {
defer transaction.Rollback() defer func() { _ = transaction.Rollback() }()
selectQuery, args, buildErr := s.statementBuilder. selectQuery, args, buildErr := s.statementBuilder.
Select(sqlReleaseTableKeyColumn). Select(sqlReleaseTableKeyColumn).
@ -559,18 +559,18 @@ func (s *SQL) Create(key string, rel release.Releaser) error {
v, v,
).ToSql() ).ToSql()
if err != nil { if err != nil {
defer transaction.Rollback() defer func() { _ = transaction.Rollback() }()
s.Logger().Debug("failed to build insert query", slog.Any("error", err)) s.Logger().Debug("failed to build insert query", slog.Any("error", err))
return err return err
} }
if _, err := transaction.Exec(insertLabelsQuery, args...); err != nil { 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)) s.Logger().Debug("failed to write Labels", slog.Any("error", err))
return err return err
} }
} }
defer transaction.Commit() defer func() { _ = transaction.Commit() }()
return nil return nil
} }
@ -646,10 +646,10 @@ func (s *SQL) Delete(key string) (release.Releaser, error) {
release, err := decodeRelease(record.Body) release, err := decodeRelease(record.Body)
if err != nil { if err != nil {
s.Logger().Debug("failed to decode release", slog.String("key", key), slog.Any("error", err)) s.Logger().Debug("failed to decode release", slog.String("key", key), slog.Any("error", err))
transaction.Rollback() _ = transaction.Rollback()
return nil, err return nil, err
} }
defer transaction.Commit() defer func() { _ = transaction.Commit() }()
deleteQuery, args, err := s.statementBuilder. deleteQuery, args, err := s.statementBuilder.
Delete(sqlReleaseTableName). Delete(sqlReleaseTableName).

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

Loading…
Cancel
Save