refactor: resolve name collision, improve naming conventions, and correct spelling errors.

* Resolve name collision with imported package name.
* Explicitly indicate unhandled responses.
* Rename variables to follow camelCase naming convention.
* Correct spelling errors.

Signed-off-by: ifuryst <ifuryst@gmail.com>
pull/13148/head
ifuryst 1 year ago
parent ff03c66d44
commit 4344999f9d
No known key found for this signature in database
GPG Key ID: 94821A6706B0E81B

@ -104,7 +104,7 @@ specific upcoming bugfix or feature release could fall into one of two different
Issues and PRs which are deemed backwards-incompatible may be added to the discussion items for Issues and PRs which are deemed backwards-incompatible may be added to the discussion items for
Helm 4 with [label:v4.x](https://github.com/helm/helm/labels/v4.x). An issue or PR that we are not Helm 4 with [label:v4.x](https://github.com/helm/helm/labels/v4.x). An issue or PR that we are not
sure we will be addressing will not be added to any milestone. sure if we will be addressing will not be added to any milestone.
A milestone (and hence release) can be closed when all outstanding issues/PRs have been closed A milestone (and hence release) can be closed when all outstanding issues/PRs have been closed
or moved to another milestone and the associated release has been published. or moved to another milestone and the associated release has been published.
@ -115,7 +115,7 @@ Helm maintains a strong commitment to backward compatibility. All of our changes
formats are backward compatible from one major release to the next. No features, flags, or commands formats are backward compatible from one major release to the next. No features, flags, or commands
are removed or substantially modified (unless we need to fix a security issue). are removed or substantially modified (unless we need to fix a security issue).
We also remain committed to not changing publicly accessible Go library definitions inside of the `pkg/` directory of our source code in a non-backwards-compatible way. We also remain committed to not changing publicly accessible Go library definitions inside the `pkg/` directory of our source code in a non-backwards-compatible way.
For more details on Helms minor and patch release backwards-compatibility rules, please read [HIP-0004](https://github.com/helm/community/blob/main/hips/hip-0004.md) For more details on Helms minor and patch release backwards-compatibility rules, please read [HIP-0004](https://github.com/helm/community/blob/main/hips/hip-0004.md)
@ -144,8 +144,8 @@ There are 5 types of issues (each with their own corresponding [label](#labels))
discussion, these can turn into `feature` or `bug` issues. discussion, these can turn into `feature` or `bug` issues.
- `proposal`: Used for items (like this one) that propose a new ideas or functionality that require - `proposal`: Used for items (like this one) that propose a new ideas or functionality that require
a larger community discussion. This allows for feedback from others in the community before a a larger community discussion. This allows for feedback from others in the community before a
feature is actually developed. This is not needed for small additions. Final word on whether or feature is actually developed. This is not needed for small additions. Final word on whether
not a feature needs a proposal is up to the core maintainers. All issues that are proposals should a feature needs a proposal is up to the core maintainers. All issues that are proposals should
both have a label and an issue title of "Proposal: [the rest of the title]." A proposal can become both have a label and an issue title of "Proposal: [the rest of the title]." A proposal can become
a `feature` and does not require a milestone. a `feature` and does not require a milestone.
- `feature`: These track specific feature requests and ideas until they are complete. They can - `feature`: These track specific feature requests and ideas until they are complete. They can
@ -163,7 +163,7 @@ below.
2. Triage 2. Triage
- The maintainer in charge of triaging will apply the proper labels for the issue. This includes - The maintainer in charge of triaging will apply the proper labels for the issue. This includes
labels for priority, type, and metadata (such as `good first issue`). The only issue priority labels for priority, type, and metadata (such as `good first issue`). The only issue priority
we will be tracking is whether or not the issue is "critical." If additional levels are needed we will be tracking is whether the issue is "critical." If additional levels are needed
in the future, we will add them. in the future, we will add them.
- (If needed) Clean up the title to succinctly and clearly state the issue. Also ensure that - (If needed) Clean up the title to succinctly and clearly state the issue. Also ensure that
proposals are prefaced with "Proposal: [the rest of the title]". proposals are prefaced with "Proposal: [the rest of the title]".

@ -166,7 +166,7 @@ else
complete -o default -o nospace -F __start_helm %[1]s complete -o default -o nospace -F __start_helm %[1]s
fi fi
` `
fmt.Fprintf(out, renamedBinaryHook, binary) _, _ = fmt.Fprintf(out, renamedBinaryHook, binary)
} }
return err return err
@ -189,11 +189,11 @@ func runCompletionZsh(out io.Writer, cmd *cobra.Command) error {
# the user renamed the helm binary # the user renamed the helm binary
compdef _helm %[1]s compdef _helm %[1]s
` `
fmt.Fprintf(out, renamedBinaryHook, binary) _, _ = fmt.Fprintf(out, renamedBinaryHook, binary)
} }
// Cobra doesn't source zsh completion file, explicitly doing it here // Cobra doesn't source zsh completion file, explicitly doing it here
fmt.Fprintf(out, "compdef _helm helm") _, _ = fmt.Fprintf(out, "compdef _helm helm")
return err return err
} }

@ -85,11 +85,11 @@ func newCreateCmd(out io.Writer) *cobra.Command {
} }
func (o *createOptions) run(out io.Writer) error { func (o *createOptions) run(out io.Writer) error {
fmt.Fprintf(out, "Creating %s\n", o.name) _, _ = fmt.Fprintf(out, "Creating %s\n", o.name)
chartname := filepath.Base(o.name) chartName := filepath.Base(o.name)
cfile := &chart.Metadata{ chartFile := &chart.Metadata{
Name: chartname, Name: chartName,
Description: "A Helm chart for Kubernetes", Description: "A Helm chart for Kubernetes",
Type: "application", Type: "application",
Version: "0.1.0", Version: "0.1.0",
@ -99,15 +99,15 @@ func (o *createOptions) run(out io.Writer) error {
if o.starter != "" { if o.starter != "" {
// Create from the starter // Create from the starter
lstarter := filepath.Join(o.starterDir, o.starter) starterPath := filepath.Join(o.starterDir, o.starter)
// If path is absolute, we don't want to prefix it with helm starters folder // If path is absolute, we don't want to prefix it with helm starters folder
if filepath.IsAbs(o.starter) { if filepath.IsAbs(o.starter) {
lstarter = o.starter starterPath = o.starter
} }
return chartutil.CreateFrom(cfile, filepath.Dir(o.name), lstarter) return chartutil.CreateFrom(chartFile, filepath.Dir(o.name), starterPath)
} }
chartutil.Stderr = out chartutil.Stderr = out
_, err := chartutil.Create(chartname, filepath.Dir(o.name)) _, err := chartutil.Create(chartName, filepath.Dir(o.name))
return err return err
} }

@ -35,7 +35,7 @@ func TestCreateCmd(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
defer testChdir(t, dir)() defer testChdir(t, dir)()
// Run a create // Run a create command
if _, _, err := executeActionCommand("create " + cname); err != nil { if _, _, err := executeActionCommand("create " + cname); err != nil {
t.Fatalf("Failed to run create: %s", err) t.Fatalf("Failed to run create: %s", err)
} }
@ -64,24 +64,30 @@ func TestCreateStarterCmd(t *testing.T) {
ensure.HelmHome(t) ensure.HelmHome(t)
cname := "testchart" cname := "testchart"
defer resetEnv()() defer resetEnv()()
os.MkdirAll(helmpath.CachePath(), 0755) err := os.MkdirAll(helmpath.CachePath(), 0755)
if err != nil {
t.Fatalf("Could not create cache directory: %s", err)
}
defer testChdir(t, helmpath.CachePath())() defer testChdir(t, helmpath.CachePath())()
// Create a starter. // Create a starter.
starterchart := helmpath.DataPath("starters") starterChart := helmpath.DataPath("starters")
os.MkdirAll(starterchart, 0755) err = os.MkdirAll(starterChart, 0755)
if dest, err := chartutil.Create("starterchart", starterchart); err != nil { if err != nil {
t.Fatalf("Could not create starter chart: %s", err)
}
if dest, err := chartutil.Create("starterChart", starterChart); err != nil {
t.Fatalf("Could not create chart: %s", err) t.Fatalf("Could not create chart: %s", err)
} else { } else {
t.Logf("Created %s", dest) t.Logf("Created %s", dest)
} }
tplpath := filepath.Join(starterchart, "starterchart", "templates", "foo.tpl") tplPath := filepath.Join(starterChart, "starterChart", "templates", "foo.tpl")
if err := os.WriteFile(tplpath, []byte("test"), 0644); err != nil { if err := os.WriteFile(tplPath, []byte("test"), 0644); err != nil {
t.Fatalf("Could not write template: %s", err) t.Fatalf("Could not write template: %s", err)
} }
// Run a create // Run a create command
if _, _, err := executeActionCommand(fmt.Sprintf("create --starter=starterchart %s", cname)); err != nil { if _, _, err := executeActionCommand(fmt.Sprintf("create --starter=starterChart %s", cname)); err != nil {
t.Errorf("Failed to run create: %s", err) t.Errorf("Failed to run create: %s", err)
return return
} }
@ -131,24 +137,30 @@ func TestCreateStarterAbsoluteCmd(t *testing.T) {
cname := "testchart" cname := "testchart"
// Create a starter. // Create a starter.
starterchart := helmpath.DataPath("starters") starterChart := helmpath.DataPath("starters")
os.MkdirAll(starterchart, 0755) err := os.MkdirAll(starterChart, 0755)
if dest, err := chartutil.Create("starterchart", starterchart); err != nil { if err != nil {
t.Fatalf("Could not create starter chart: %s", err)
}
if dest, err := chartutil.Create("starterChart", starterChart); err != nil {
t.Fatalf("Could not create chart: %s", err) t.Fatalf("Could not create chart: %s", err)
} else { } else {
t.Logf("Created %s", dest) t.Logf("Created %s", dest)
} }
tplpath := filepath.Join(starterchart, "starterchart", "templates", "foo.tpl") tplPath := filepath.Join(starterChart, "starterChart", "templates", "foo.tpl")
if err := os.WriteFile(tplpath, []byte("test"), 0644); err != nil { if err := os.WriteFile(tplPath, []byte("test"), 0644); err != nil {
t.Fatalf("Could not write template: %s", err) t.Fatalf("Could not write template: %s", err)
} }
os.MkdirAll(helmpath.CachePath(), 0755) err = os.MkdirAll(helmpath.CachePath(), 0755)
if err != nil {
t.Fatalf("Could not create cache directory: %s", err)
}
defer testChdir(t, helmpath.CachePath())() defer testChdir(t, helmpath.CachePath())()
starterChartPath := filepath.Join(starterchart, "starterchart") starterChartPath := filepath.Join(starterChart, "starterChart")
// Run a create // Run a create command
if _, _, err := executeActionCommand(fmt.Sprintf("create --starter=%s %s", starterChartPath, cname)); err != nil { if _, _, err := executeActionCommand(fmt.Sprintf("create --starter=%s %s", starterChartPath, cname)); err != nil {
t.Errorf("Failed to run create: %s", err) t.Errorf("Failed to run create: %s", err)
return return

@ -107,11 +107,11 @@ func newDependencyListCmd(out io.Writer) *cobra.Command {
Long: dependencyListDesc, Long: dependencyListDesc,
Args: require.MaximumNArgs(1), Args: require.MaximumNArgs(1),
RunE: func(_ *cobra.Command, args []string) error { RunE: func(_ *cobra.Command, args []string) error {
chartpath := "." chartPath := "."
if len(args) > 0 { if len(args) > 0 {
chartpath = filepath.Clean(args[0]) chartPath = filepath.Clean(args[0])
} }
return client.List(chartpath, out) return client.List(chartPath, out)
}, },
} }

@ -16,6 +16,7 @@ limitations under the License.
package main package main
import ( import (
"errors"
"fmt" "fmt"
"io" "io"
"os" "os"
@ -50,13 +51,13 @@ func newDependencyBuildCmd(cfg *action.Configuration, out io.Writer) *cobra.Comm
Long: dependencyBuildDesc, Long: dependencyBuildDesc,
Args: require.MaximumNArgs(1), Args: require.MaximumNArgs(1),
RunE: func(_ *cobra.Command, args []string) error { RunE: func(_ *cobra.Command, args []string) error {
chartpath := "." chartPath := "."
if len(args) > 0 { if len(args) > 0 {
chartpath = filepath.Clean(args[0]) chartPath = filepath.Clean(args[0])
} }
man := &downloader.Manager{ man := &downloader.Manager{
Out: out, Out: out,
ChartPath: chartpath, ChartPath: chartPath,
Keyring: client.Keyring, Keyring: client.Keyring,
SkipUpdate: client.SkipRefresh, SkipUpdate: client.SkipRefresh,
Getters: getter.All(settings), Getters: getter.All(settings),
@ -69,7 +70,8 @@ func newDependencyBuildCmd(cfg *action.Configuration, out io.Writer) *cobra.Comm
man.Verify = downloader.VerifyIfPossible man.Verify = downloader.VerifyIfPossible
} }
err := man.Build() err := man.Build()
if e, ok := err.(downloader.ErrRepoNotFound); ok { var e downloader.ErrRepoNotFound
if errors.As(err, &e) {
return fmt.Errorf("%s. Please add the missing repos via 'helm repo add'", e.Error()) return fmt.Errorf("%s. Please add the missing repos via 'helm repo add'", e.Error())
} }
return err return err

@ -106,7 +106,7 @@ func TestDependencyUpdateCmd(t *testing.T) {
{Name: "reqtest", Version: "0.1.0", Repository: srv.URL()}, {Name: "reqtest", Version: "0.1.0", Repository: srv.URL()},
{Name: "compressedchart", Version: "0.3.0", Repository: srv.URL()}, {Name: "compressedchart", Version: "0.3.0", Repository: srv.URL()},
} }
if err := chartutil.SaveChartfile(dir(chartname, "Chart.yaml"), md); err != nil { if err := chartutil.SaveChartFile(dir(chartname, "Chart.yaml"), md); err != nil {
t.Fatal(err) t.Fatal(err)
} }

@ -53,10 +53,10 @@ func newEnvCmd(out io.Writer) *cobra.Command {
keys := getSortedEnvVarKeys() keys := getSortedEnvVarKeys()
for _, k := range keys { for _, k := range keys {
fmt.Fprintf(out, "%s=\"%s\"\n", k, envVars[k]) _, _ = fmt.Fprintf(out, "%s=\"%s\"\n", k, envVars[k])
} }
} else { } else {
fmt.Fprintf(out, "%s\n", envVars[args[0]]) _, _ = fmt.Fprintf(out, "%s\n", envVars[args[0]])
} }
}, },
} }

@ -60,7 +60,7 @@ func addChartPathOptionsFlags(f *pflag.FlagSet, c *action.ChartPathOptions) {
f.StringVar(&c.Password, "password", "", "chart repository password where to locate the requested chart") f.StringVar(&c.Password, "password", "", "chart repository password where to locate the requested chart")
f.StringVar(&c.CertFile, "cert-file", "", "identify HTTPS client using this SSL certificate file") f.StringVar(&c.CertFile, "cert-file", "", "identify HTTPS client using this SSL certificate file")
f.StringVar(&c.KeyFile, "key-file", "", "identify HTTPS client using this SSL key file") f.StringVar(&c.KeyFile, "key-file", "", "identify HTTPS client using this SSL key file")
f.BoolVar(&c.InsecureSkipTLSverify, "insecure-skip-tls-verify", false, "skip tls certificate checks for the chart download") f.BoolVar(&c.InsecureSkipTLSVerify, "insecure-skip-tls-verify", false, "skip tls certificate checks for the chart download")
f.BoolVar(&c.PlainHTTP, "plain-http", false, "use insecure HTTP connections for the chart download") f.BoolVar(&c.PlainHTTP, "plain-http", false, "use insecure HTTP connections for the chart download")
f.StringVar(&c.CaFile, "ca-file", "", "verify certificates of HTTPS-enabled servers using this CA bundle") f.StringVar(&c.CaFile, "ca-file", "", "verify certificates of HTTPS-enabled servers using this CA bundle")
f.BoolVar(&c.PassCredentialsAll, "pass-credentials", false, "pass credentials to all domains") f.BoolVar(&c.PassCredentialsAll, "pass-credentials", false, "pass credentials to all domains")
@ -107,11 +107,11 @@ func (o *outputValue) Type() string {
} }
func (o *outputValue) Set(s string) error { func (o *outputValue) Set(s string) error {
outfmt, err := output.ParseFormat(s) outFmt, err := output.ParseFormat(s)
if err != nil { if err != nil {
return err return err
} }
*o = outputValue(outfmt) *o = outputValue(outFmt)
return nil return nil
} }
@ -240,9 +240,9 @@ func addKlogFlags(fs *pflag.FlagSet) {
if fs.Lookup(fl.Name) != nil { if fs.Lookup(fl.Name) != nil {
return return
} }
newflag := pflag.PFlagFromGoFlag(fl) newFlag := pflag.PFlagFromGoFlag(fl)
newflag.Hidden = true newFlag.Hidden = true
fs.AddFlag(newflag) fs.AddFlag(newFlag)
}) })
} }

@ -53,7 +53,7 @@ func newGetHooksCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
return err return err
} }
for _, hook := range res.Hooks { for _, hook := range res.Hooks {
fmt.Fprintf(out, "---\n# Source: %s\n%s\n", hook.Path, hook.Manifest) _, _ = fmt.Fprintf(out, "---\n# Source: %s\n%s\n", hook.Path, hook.Manifest)
} }
return nil return nil
}, },

@ -54,7 +54,7 @@ func newGetManifestCmd(cfg *action.Configuration, out io.Writer) *cobra.Command
if err != nil { if err != nil {
return err return err
} }
fmt.Fprintln(out, res.Manifest) _, _ = fmt.Fprintln(out, res.Manifest)
return nil return nil
}, },
} }

@ -33,7 +33,7 @@ type metadataWriter struct {
} }
func newGetMetadataCmd(cfg *action.Configuration, out io.Writer) *cobra.Command { func newGetMetadataCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
var outfmt output.Format var outFmt output.Format
client := action.NewGetMetadata(cfg) client := action.NewGetMetadata(cfg)
cmd := &cobra.Command{ cmd := &cobra.Command{
@ -51,7 +51,7 @@ func newGetMetadataCmd(cfg *action.Configuration, out io.Writer) *cobra.Command
if err != nil { if err != nil {
return err return err
} }
return outfmt.Write(out, &metadataWriter{releaseMetadata}) return outFmt.Write(out, &metadataWriter{releaseMetadata})
}, },
} }
@ -68,7 +68,7 @@ func newGetMetadataCmd(cfg *action.Configuration, out io.Writer) *cobra.Command
log.Fatal(err) log.Fatal(err)
} }
bindOutputFlag(cmd, &outfmt) bindOutputFlag(cmd, &outFmt)
return cmd return cmd
} }

@ -51,7 +51,7 @@ func newGetNotesCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
return err return err
} }
if len(res.Info.Notes) > 0 { if len(res.Info.Notes) > 0 {
fmt.Fprintf(out, "NOTES:\n%s\n", res.Info.Notes) _, _ = fmt.Fprintf(out, "NOTES:\n%s\n", res.Info.Notes)
} }
return nil return nil
}, },

@ -38,7 +38,7 @@ type valuesWriter struct {
} }
func newGetValuesCmd(cfg *action.Configuration, out io.Writer) *cobra.Command { func newGetValuesCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
var outfmt output.Format var outFmt output.Format
client := action.NewGetValues(cfg) client := action.NewGetValues(cfg)
cmd := &cobra.Command{ cmd := &cobra.Command{
@ -57,7 +57,7 @@ func newGetValuesCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
if err != nil { if err != nil {
return err return err
} }
return outfmt.Write(out, &valuesWriter{vals, client.AllValues}) return outFmt.Write(out, &valuesWriter{vals, client.AllValues})
}, },
} }
@ -75,16 +75,16 @@ func newGetValuesCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
} }
f.BoolVarP(&client.AllValues, "all", "a", false, "dump all (computed) values") f.BoolVarP(&client.AllValues, "all", "a", false, "dump all (computed) values")
bindOutputFlag(cmd, &outfmt) bindOutputFlag(cmd, &outFmt)
return cmd return cmd
} }
func (v valuesWriter) WriteTable(out io.Writer) error { func (v valuesWriter) WriteTable(out io.Writer) error {
if v.allValues { if v.allValues {
fmt.Fprintln(out, "COMPUTED VALUES:") _, _ = fmt.Fprintln(out, "COMPUTED VALUES:")
} else { } else {
fmt.Fprintln(out, "USER-SUPPLIED VALUES:") _, _ = fmt.Fprintln(out, "USER-SUPPLIED VALUES:")
} }
return output.EncodeYAML(out, v.vals) return output.EncodeYAML(out, v.vals)
} }

@ -17,6 +17,7 @@ limitations under the License.
package main // import "helm.sh/helm/v3/cmd/helm" package main // import "helm.sh/helm/v3/cmd/helm"
import ( import (
"errors"
"fmt" "fmt"
"io" "io"
"log" "log"
@ -46,13 +47,13 @@ func init() {
func debug(format string, v ...interface{}) { func debug(format string, v ...interface{}) {
if settings.Debug { if settings.Debug {
format = fmt.Sprintf("[debug] %s\n", format) format = fmt.Sprintf("[debug] %s\n", format)
log.Output(2, fmt.Sprintf(format, v...)) _ = log.Output(2, fmt.Sprintf(format, v...))
} }
} }
func warning(format string, v ...interface{}) { func warning(format string, v ...interface{}) {
format = fmt.Sprintf("WARNING: %s\n", format) format = fmt.Sprintf("WARNING: %s\n", format)
fmt.Fprintf(os.Stderr, format, v...) _, _ = fmt.Fprintf(os.Stderr, format, v...)
} }
func main() { func main() {
@ -82,8 +83,9 @@ func main() {
if err := cmd.Execute(); err != nil { if err := cmd.Execute(); err != nil {
debug("%+v", err) debug("%+v", err)
switch e := err.(type) { var e pluginError
case pluginError: switch {
case errors.As(err, &e):
os.Exit(e.code) os.Exit(e.code)
default: default:
os.Exit(1) os.Exit(1)
@ -114,7 +116,7 @@ func loadReleasesInMemory(actionConfig *action.Configuration) {
log.Fatal("Unable to read memory driver data", err) log.Fatal("Unable to read memory driver data", err)
} }
releases := []*release.Release{} var releases []*release.Release
if err := yaml.Unmarshal(b, &releases); err != nil { if err := yaml.Unmarshal(b, &releases); err != nil {
log.Fatal("Unable to unmarshal memory driver data: ", err) log.Fatal("Unable to unmarshal memory driver data: ", err)
} }

@ -52,7 +52,7 @@ The historical release set is printed as a formatted table, e.g:
func newHistoryCmd(cfg *action.Configuration, out io.Writer) *cobra.Command { func newHistoryCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
client := action.NewHistory(cfg) client := action.NewHistory(cfg)
var outfmt output.Format var outFmt output.Format
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "history RELEASE_NAME", Use: "history RELEASE_NAME",
@ -72,13 +72,13 @@ func newHistoryCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
return err return err
} }
return outfmt.Write(out, history) return outFmt.Write(out, history)
}, },
} }
f := cmd.Flags() f := cmd.Flags()
f.IntVar(&client.Max, "max", 256, "maximum number of revision to include in history") f.IntVar(&client.Max, "max", 256, "maximum number of revision to include in history")
bindOutputFlag(cmd, &outfmt) bindOutputFlag(cmd, &outFmt)
return cmd return cmd
} }
@ -136,7 +136,7 @@ func getHistory(client *action.History, name string) (releaseHistory, error) {
func getReleaseHistory(rls []*release.Release) (history releaseHistory) { func getReleaseHistory(rls []*release.Release) (history releaseHistory) {
for i := len(rls) - 1; i >= 0; i-- { for i := len(rls) - 1; i >= 0; i-- {
r := rls[i] r := rls[i]
c := formatChartname(r.Chart) c := formatChartName(r.Chart)
s := r.Info.Status.String() s := r.Info.Status.String()
v := r.Version v := r.Version
d := r.Info.Description d := r.Info.Description
@ -159,7 +159,7 @@ func getReleaseHistory(rls []*release.Release) (history releaseHistory) {
return history return history
} }
func formatChartname(c *chart.Chart) string { func formatChartName(c *chart.Chart) string {
if c == nil || c.Metadata == nil { if c == nil || c.Metadata == nil {
// This is an edge case that has happened in prod, though we don't // This is an edge case that has happened in prod, though we don't
// know how: https://github.com/helm/helm/issues/1347 // know how: https://github.com/helm/helm/issues/1347
@ -177,22 +177,15 @@ func formatAppVersion(c *chart.Chart) string {
return c.AppVersion() return c.AppVersion()
} }
func min(x, y int) int {
if x < y {
return x
}
return y
}
func compListRevisions(_ string, cfg *action.Configuration, releaseName string) ([]string, cobra.ShellCompDirective) { func compListRevisions(_ string, cfg *action.Configuration, releaseName string) ([]string, cobra.ShellCompDirective) {
client := action.NewHistory(cfg) client := action.NewHistory(cfg)
var revisions []string var revisions []string
if hist, err := client.Run(releaseName); err == nil { if hist, err := client.Run(releaseName); err == nil {
for _, release := range hist { for _, rel := range hist {
appVersion := fmt.Sprintf("App: %s", release.Chart.Metadata.AppVersion) appVersion := fmt.Sprintf("App: %s", rel.Chart.Metadata.AppVersion)
chartDesc := fmt.Sprintf("Chart: %s-%s", release.Chart.Metadata.Name, release.Chart.Metadata.Version) chartDesc := fmt.Sprintf("Chart: %s-%s", rel.Chart.Metadata.Name, rel.Chart.Metadata.Version)
revisions = append(revisions, fmt.Sprintf("%s\t%s, %s", strconv.Itoa(release.Version), appVersion, chartDesc)) revisions = append(revisions, fmt.Sprintf("%s\t%s, %s", strconv.Itoa(rel.Version), appVersion, chartDesc))
} }
return revisions, cobra.ShellCompDirectiveNoFileComp return revisions, cobra.ShellCompDirectiveNoFileComp
} }

@ -129,7 +129,7 @@ charts in a repository, use 'helm search'.
func newInstallCmd(cfg *action.Configuration, out io.Writer) *cobra.Command { func newInstallCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
client := action.NewInstall(cfg) client := action.NewInstall(cfg)
valueOpts := &values.Options{} valueOpts := &values.Options{}
var outfmt output.Format var outFmt output.Format
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "install [NAME] [CHART]", Use: "install [NAME] [CHART]",
@ -141,14 +141,14 @@ func newInstallCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
}, },
RunE: func(_ *cobra.Command, args []string) error { RunE: func(_ *cobra.Command, args []string) error {
registryClient, err := newRegistryClient(client.CertFile, client.KeyFile, client.CaFile, registryClient, err := newRegistryClient(client.CertFile, client.KeyFile, client.CaFile,
client.InsecureSkipTLSverify, client.PlainHTTP) client.InsecureSkipTLSVerify, client.PlainHTTP)
if err != nil { if err != nil {
return fmt.Errorf("missing registry client: %w", err) return fmt.Errorf("missing registry client: %w", err)
} }
client.SetRegistryClient(registryClient) client.SetRegistryClient(registryClient)
// This is for the case where "" is specifically passed in as a // This is for the case where "" is specifically passed in as a
// value. When there is no value passed in NoOptDefVal will be used // value. When there is no value passed in NoOptDefVal will be used,
// and it is set to client. See addInstallFlags. // and it is set to client. See addInstallFlags.
if client.DryRunOption == "" { if client.DryRunOption == "" {
client.DryRunOption = "none" client.DryRunOption = "none"
@ -158,16 +158,16 @@ func newInstallCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
return errors.Wrap(err, "INSTALLATION FAILED") return errors.Wrap(err, "INSTALLATION FAILED")
} }
return outfmt.Write(out, &statusPrinter{rel, settings.Debug, false, false, false, client.HideNotes}) return outFmt.Write(out, &statusPrinter{rel, settings.Debug, false, false, false, client.HideNotes})
}, },
} }
addInstallFlags(cmd, cmd.Flags(), client, valueOpts) addInstallFlags(cmd, cmd.Flags(), client, valueOpts)
// hide-secret is not available in all places the install flags are used so // the hide-secret is not available in all places where the install flags are used, so
// it is added separately // it is added separately
f := cmd.Flags() f := cmd.Flags()
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")
bindOutputFlag(cmd, &outfmt) bindOutputFlag(cmd, &outFmt)
bindPostRenderFlag(cmd, &client.PostRenderer) bindPostRenderFlag(cmd, &client.PostRenderer)
return cmd return cmd
@ -226,13 +226,13 @@ func runInstall(args []string, client *action.Install, valueOpts *values.Options
client.Version = ">0.0.0-0" client.Version = ">0.0.0-0"
} }
name, chart, err := client.NameAndChart(args) name, chartName, err := client.NameAndChart(args)
if err != nil { if err != nil {
return nil, err return nil, err
} }
client.ReleaseName = name client.ReleaseName = name
cp, err := client.ChartPathOptions.LocateChart(chart, settings) cp, err := client.ChartPathOptions.LocateChart(chartName, settings)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -308,7 +308,7 @@ func runInstall(args []string, client *action.Install, valueOpts *values.Options
signal.Notify(cSignal, os.Interrupt, syscall.SIGTERM) signal.Notify(cSignal, os.Interrupt, syscall.SIGTERM)
go func() { go func() {
<-cSignal <-cSignal
fmt.Fprintf(out, "Release %s has been cancelled.\n", args[0]) _, _ = fmt.Fprintf(out, "Release %s has been cancelled.\n", args[0])
cancel() cancel()
}() }()

@ -67,7 +67,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 { _ = 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))
@ -103,7 +103,7 @@ func newLintCmd(out io.Writer) *cobra.Command {
continue continue
} }
fmt.Fprintf(&message, "==> Linting %s\n", path) _, _ = fmt.Fprintf(&message, "==> Linting %s\n", path)
// All the Errors that are generated by a chart // All the Errors that are generated by a chart
// that failed a lint will be included in the // that failed a lint will be included in the
@ -111,13 +111,13 @@ func newLintCmd(out io.Writer) *cobra.Command {
// the Errors if there are no Messages. // the Errors if there are no Messages.
if len(result.Messages) == 0 { if len(result.Messages) == 0 {
for _, err := range result.Errors { for _, err := range result.Errors {
fmt.Fprintf(&message, "Error %s\n", err) _, _ = fmt.Fprintf(&message, "Error %s\n", err)
} }
} }
for _, msg := range result.Messages { for _, msg := range result.Messages {
if !client.Quiet || msg.Severity > support.InfoSev { if !client.Quiet || msg.Severity > support.InfoSev {
fmt.Fprintf(&message, "%s\n", msg) _, _ = fmt.Fprintf(&message, "%s\n", msg)
} }
} }
@ -128,17 +128,17 @@ func newLintCmd(out io.Writer) *cobra.Command {
// Adding extra new line here to break up the // Adding extra new line here to break up the
// results, stops this from being a big wall of // results, stops this from being a big wall of
// text and makes it easier to follow. // text and makes it easier to follow.
fmt.Fprint(&message, "\n") _, _ = fmt.Fprint(&message, "\n")
} }
fmt.Fprint(out, message.String()) _, _ = fmt.Fprint(out, message.String())
summary := fmt.Sprintf("%d chart(s) linted, %d chart(s) failed", len(paths), failed) summary := fmt.Sprintf("%d chart(s) linted, %d chart(s) failed", len(paths), failed)
if failed > 0 { if failed > 0 {
return errors.New(summary) return errors.New(summary)
} }
if !client.Quiet || errorsOrWarnings > 0 { if !client.Quiet || errorsOrWarnings > 0 {
fmt.Fprintln(out, summary) _, _ = fmt.Fprintln(out, summary)
} }
return nil return nil
}, },

@ -60,7 +60,7 @@ flag with the '--offset' flag allows you to page through results.
func newListCmd(cfg *action.Configuration, out io.Writer) *cobra.Command { func newListCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
client := action.NewList(cfg) client := action.NewList(cfg)
var outfmt output.Format var outFmt output.Format
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "list", Use: "list",
@ -92,20 +92,20 @@ 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) _ = output.EncodeJSON(out, names)
return nil return nil
case "yaml": case "yaml":
output.EncodeYAML(out, names) _ = output.EncodeYAML(out, names)
return nil return nil
case "table": case "table":
for _, res := range results { for _, res := range results {
fmt.Fprintln(out, res.Name) _, _ = fmt.Fprintln(out, res.Name)
} }
return nil return nil
} }
} }
return outfmt.Write(out, newReleaseListWriter(results, client.TimeFormat, client.NoHeaders)) return outFmt.Write(out, newReleaseListWriter(results, client.TimeFormat, client.NoHeaders))
}, },
} }
@ -127,7 +127,7 @@ func newListCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
f.IntVar(&client.Offset, "offset", 0, "next release index in the list, used to offset from start value") f.IntVar(&client.Offset, "offset", 0, "next release index in the list, used to offset from start value")
f.StringVarP(&client.Filter, "filter", "f", "", "a regular expression (Perl compatible). Any releases that match the expression will be included in the results") f.StringVarP(&client.Filter, "filter", "f", "", "a regular expression (Perl compatible). Any releases that match the expression will be included in the results")
f.StringVarP(&client.Selector, "selector", "l", "", "Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Works only for secret(default) and configmap storage backends.") f.StringVarP(&client.Selector, "selector", "l", "", "Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Works only for secret(default) and configmap storage backends.")
bindOutputFlag(cmd, &outfmt) bindOutputFlag(cmd, &outFmt)
return cmd return cmd
} }
@ -156,7 +156,7 @@ func newReleaseListWriter(releases []*release.Release, timeFormat string, noHead
Namespace: r.Namespace, Namespace: r.Namespace,
Revision: strconv.Itoa(r.Version), Revision: strconv.Itoa(r.Version),
Status: r.Info.Status.String(), Status: r.Info.Status.String(),
Chart: formatChartname(r.Chart), Chart: formatChartName(r.Chart),
AppVersion: formatAppVersion(r.Chart), AppVersion: formatAppVersion(r.Chart),
} }
@ -225,7 +225,7 @@ func compListReleases(toComplete string, ignoredReleaseNames []string, cfg *acti
client := action.NewList(cfg) client := action.NewList(cfg)
client.All = true client.All = true
client.Limit = 0 client.Limit = 0
// Do not filter so as to get the entire list of releases. // Do not filter to get the entire list of releases.
// This will allow zsh and fish to match completion choices // This will allow zsh and fish to match completion choices
// on other criteria then prefix. For example: // on other criteria then prefix. For example:
// helm status ingress<TAB> // helm status ingress<TAB>

@ -58,7 +58,7 @@ func loadPlugins(baseCmd *cobra.Command, out io.Writer) {
found, err := plugin.FindPlugins(settings.PluginsDirectory) found, err := plugin.FindPlugins(settings.PluginsDirectory)
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "failed to load plugins: %s\n", err) _, _ = fmt.Fprintf(os.Stderr, "failed to load plugins: %s\n", err)
return return
} }

@ -104,7 +104,7 @@ func newPackageCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
if err != nil { if err != nil {
return err return err
} }
fmt.Fprintf(out, "Successfully packaged chart and saved it to: %s\n", p) _, _ = fmt.Fprintf(out, "Successfully packaged chart and saved it to: %s\n", p)
} }
return nil return nil
}, },

@ -89,6 +89,6 @@ func (o *pluginInstallOptions) run(out io.Writer) error {
return err return err
} }
fmt.Fprintf(out, "Installed plugin: %s\n", p.Metadata.Name) _, _ = fmt.Fprintf(out, "Installed plugin: %s\n", p.Metadata.Name)
return nil return nil
} }

@ -43,7 +43,7 @@ func newPluginListCmd(out io.Writer) *cobra.Command {
for _, p := range plugins { for _, p := range plugins {
table.AddRow(p.Metadata.Name, p.Metadata.Version, p.Metadata.Description) table.AddRow(p.Metadata.Name, p.Metadata.Version, p.Metadata.Description)
} }
fmt.Fprintln(out, table) _, _ = fmt.Fprintln(out, table)
return nil return nil
}, },
} }
@ -58,16 +58,16 @@ func filterPlugins(plugins []*plugin.Plugin, ignoredPluginNames []string) []*plu
} }
var filteredPlugins []*plugin.Plugin var filteredPlugins []*plugin.Plugin
for _, plugin := range plugins { for _, plg := range plugins {
found := false found := false
for _, ignoredName := range ignoredPluginNames { for _, ignoredName := range ignoredPluginNames {
if plugin.Metadata.Name == ignoredName { if plg.Metadata.Name == ignoredName {
found = true found = true
break break
} }
} }
if !found { if !found {
filteredPlugins = append(filteredPlugins, plugin) filteredPlugins = append(filteredPlugins, plg)
} }
} }

@ -71,7 +71,7 @@ func (o *pluginUninstallOptions) run(out io.Writer) error {
if err := uninstallPlugin(found); err != nil { if err := uninstallPlugin(found); err != nil {
errorPlugins = append(errorPlugins, fmt.Sprintf("Failed to uninstall plugin %s, got error (%v)", name, err)) errorPlugins = append(errorPlugins, fmt.Sprintf("Failed to uninstall plugin %s, got error (%v)", name, err))
} else { } else {
fmt.Fprintf(out, "Uninstalled plugin: %s\n", name) _, _ = fmt.Fprintf(out, "Uninstalled plugin: %s\n", name)
} }
} else { } else {
errorPlugins = append(errorPlugins, fmt.Sprintf("Plugin: %s not found", name)) errorPlugins = append(errorPlugins, fmt.Sprintf("Plugin: %s not found", name))

@ -74,7 +74,7 @@ func (o *pluginUpdateOptions) run(out io.Writer) error {
if err := updatePlugin(found); err != nil { if err := updatePlugin(found); err != nil {
errorPlugins = append(errorPlugins, fmt.Sprintf("Failed to update plugin %s, got error (%v)", name, err)) errorPlugins = append(errorPlugins, fmt.Sprintf("Failed to update plugin %s, got error (%v)", name, err))
} else { } else {
fmt.Fprintf(out, "Updated plugin: %s\n", name) _, _ = fmt.Fprintf(out, "Updated plugin: %s\n", name)
} }
} else { } else {
errorPlugins = append(errorPlugins, fmt.Sprintf("Plugin: %s not found", name)) errorPlugins = append(errorPlugins, fmt.Sprintf("Plugin: %s not found", name))

@ -65,7 +65,7 @@ func newPullCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
} }
registryClient, err := newRegistryClient(client.CertFile, client.KeyFile, client.CaFile, registryClient, err := newRegistryClient(client.CertFile, client.KeyFile, client.CaFile,
client.InsecureSkipTLSverify, client.PlainHTTP) client.InsecureSkipTLSVerify, client.PlainHTTP)
if err != nil { if err != nil {
return fmt.Errorf("missing registry client: %w", err) return fmt.Errorf("missing registry client: %w", err)
} }
@ -76,7 +76,7 @@ func newPullCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
if err != nil { if err != nil {
return err return err
} }
fmt.Fprint(out, output) _, _ = fmt.Fprint(out, output)
} }
return nil return nil
}, },

@ -38,7 +38,7 @@ type registryPushOptions struct {
certFile string certFile string
keyFile string keyFile string
caFile string caFile string
insecureSkipTLSverify bool insecureSkipTLSVerify bool
plainHTTP bool plainHTTP bool
} }
@ -68,7 +68,7 @@ func newPushCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
return nil, cobra.ShellCompDirectiveNoFileComp return nil, cobra.ShellCompDirectiveNoFileComp
}, },
RunE: func(_ *cobra.Command, args []string) error { RunE: func(_ *cobra.Command, args []string) error {
registryClient, err := newRegistryClient(o.certFile, o.keyFile, o.caFile, o.insecureSkipTLSverify, o.plainHTTP) registryClient, err := newRegistryClient(o.certFile, o.keyFile, o.caFile, o.insecureSkipTLSVerify, o.plainHTTP)
if err != nil { if err != nil {
return fmt.Errorf("missing registry client: %w", err) return fmt.Errorf("missing registry client: %w", err)
} }
@ -77,7 +77,7 @@ func newPushCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
remote := args[1] remote := args[1]
client := action.NewPushWithOpts(action.WithPushConfig(cfg), client := action.NewPushWithOpts(action.WithPushConfig(cfg),
action.WithTLSClientConfig(o.certFile, o.keyFile, o.caFile), action.WithTLSClientConfig(o.certFile, o.keyFile, o.caFile),
action.WithInsecureSkipTLSVerify(o.insecureSkipTLSverify), action.WithInsecureSkipTLSVerify(o.insecureSkipTLSVerify),
action.WithPlainHTTP(o.plainHTTP), action.WithPlainHTTP(o.plainHTTP),
action.WithPushOptWriter(out)) action.WithPushOptWriter(out))
client.Settings = settings client.Settings = settings
@ -85,7 +85,7 @@ func newPushCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
if err != nil { if err != nil {
return err return err
} }
fmt.Fprint(out, output) _, _ = fmt.Fprint(out, output)
return nil return nil
}, },
} }
@ -94,7 +94,7 @@ func newPushCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
f.StringVar(&o.certFile, "cert-file", "", "identify registry client using this SSL certificate file") f.StringVar(&o.certFile, "cert-file", "", "identify registry client using this SSL certificate file")
f.StringVar(&o.keyFile, "key-file", "", "identify registry client using this SSL key file") f.StringVar(&o.keyFile, "key-file", "", "identify registry client using this SSL key file")
f.StringVar(&o.caFile, "ca-file", "", "verify certificates of HTTPS-enabled servers using this CA bundle") f.StringVar(&o.caFile, "ca-file", "", "verify certificates of HTTPS-enabled servers using this CA bundle")
f.BoolVar(&o.insecureSkipTLSverify, "insecure-skip-tls-verify", false, "skip tls certificate checks for the chart upload") f.BoolVar(&o.insecureSkipTLSVerify, "insecure-skip-tls-verify", false, "skip tls certificate checks for the chart upload")
f.BoolVar(&o.plainHTTP, "plain-http", false, "use insecure HTTP connections for the chart upload") f.BoolVar(&o.plainHTTP, "plain-http", false, "use insecure HTTP connections for the chart upload")
return cmd return cmd

@ -39,7 +39,7 @@ The tests to be run are defined in the chart that was installed.
func newReleaseTestCmd(cfg *action.Configuration, out io.Writer) *cobra.Command { func newReleaseTestCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
client := action.NewReleaseTesting(cfg) client := action.NewReleaseTesting(cfg)
var outfmt = output.Table var outFmt = output.Table
var outputLogs bool var outputLogs bool
var filter []string var filter []string
@ -66,19 +66,19 @@ func newReleaseTestCmd(cfg *action.Configuration, out io.Writer) *cobra.Command
} }
rel, runErr := client.Run(args[0]) rel, runErr := client.Run(args[0])
// We only return an error if we weren't even able to get the // We only return an error if we weren't even able to get the
// release, otherwise we keep going so we can print status and logs // release, otherwise we keep going, so we can print status and logs
// if requested // if requested
if runErr != nil && rel == nil { if runErr != nil && rel == nil {
return runErr return runErr
} }
if err := outfmt.Write(out, &statusPrinter{rel, settings.Debug, false, false, false, client.HideNotes}); err != nil { if err := outFmt.Write(out, &statusPrinter{rel, settings.Debug, false, false, false, client.HideNotes}); err != nil {
return err return err
} }
if outputLogs { if outputLogs {
// Print a newline to stdout to separate the output // Print a newline to stdout to separate the output
fmt.Fprintln(out) _, _ = fmt.Fprintln(out)
if err := client.GetPodLogs(out, rel); err != nil { if err := client.GetPodLogs(out, rel); err != nil {
return err return err
} }

@ -55,7 +55,7 @@ type repoAddOptions struct {
certFile string certFile string
keyFile string keyFile string
caFile string caFile string
insecureSkipTLSverify bool insecureSkipTLSVerify bool
repoFile string repoFile string
repoCache string repoCache string
@ -91,7 +91,7 @@ func newRepoAddCmd(out io.Writer) *cobra.Command {
f.StringVar(&o.certFile, "cert-file", "", "identify HTTPS client using this SSL certificate file") f.StringVar(&o.certFile, "cert-file", "", "identify HTTPS client using this SSL certificate file")
f.StringVar(&o.keyFile, "key-file", "", "identify HTTPS client using this SSL key file") f.StringVar(&o.keyFile, "key-file", "", "identify HTTPS client using this SSL key file")
f.StringVar(&o.caFile, "ca-file", "", "verify certificates of HTTPS-enabled servers using this CA bundle") f.StringVar(&o.caFile, "ca-file", "", "verify certificates of HTTPS-enabled servers using this CA bundle")
f.BoolVar(&o.insecureSkipTLSverify, "insecure-skip-tls-verify", false, "skip tls certificate checks for the repository") f.BoolVar(&o.insecureSkipTLSVerify, "insecure-skip-tls-verify", false, "skip tls certificate checks for the repository")
f.BoolVar(&o.allowDeprecatedRepos, "allow-deprecated-repos", false, "by default, this command will not allow adding official repos that have been permanently deleted. This disables that behavior") f.BoolVar(&o.allowDeprecatedRepos, "allow-deprecated-repos", false, "by default, this command will not allow adding official repos that have been permanently deleted. This disables that behavior")
f.BoolVar(&o.passCredentialsAll, "pass-credentials", false, "pass credentials to all domains") f.BoolVar(&o.passCredentialsAll, "pass-credentials", false, "pass credentials to all domains")
@ -154,9 +154,9 @@ func (o *repoAddOptions) run(out io.Writer) error {
o.password = password o.password = password
} else { } else {
fd := int(os.Stdin.Fd()) fd := int(os.Stdin.Fd())
fmt.Fprint(out, "Password: ") _, _ = fmt.Fprint(out, "Password: ")
password, err := term.ReadPassword(fd) password, err := term.ReadPassword(fd)
fmt.Fprintln(out) _, _ = fmt.Fprintln(out)
if err != nil { if err != nil {
return err return err
} }
@ -173,7 +173,7 @@ func (o *repoAddOptions) run(out io.Writer) error {
CertFile: o.certFile, CertFile: o.certFile,
KeyFile: o.keyFile, KeyFile: o.keyFile,
CAFile: o.caFile, CAFile: o.caFile,
InsecureSkipTLSverify: o.insecureSkipTLSverify, InsecureSkipTLSverify: o.insecureSkipTLSVerify,
} }
// Check if the repo name is legal // Check if the repo name is legal
@ -194,7 +194,7 @@ func (o *repoAddOptions) run(out io.Writer) error {
} }
// The add is idempotent so do nothing // The add is idempotent so do nothing
fmt.Fprintf(out, "%q already exists with the same configuration, skipping\n", o.name) _, _ = fmt.Fprintf(out, "%q already exists with the same configuration, skipping\n", o.name)
return nil return nil
} }
@ -215,6 +215,6 @@ func (o *repoAddOptions) run(out io.Writer) error {
if err := f.WriteFile(o.repoFile, 0600); err != nil { if err := f.WriteFile(o.repoFile, 0600); err != nil {
return err return err
} }
fmt.Fprintf(out, "%q has been added to your repositories\n", o.name) _, _ = fmt.Fprintf(out, "%q has been added to your repositories\n", o.name)
return nil return nil
} }

@ -30,7 +30,7 @@ import (
) )
func newRepoListCmd(out io.Writer) *cobra.Command { func newRepoListCmd(out io.Writer) *cobra.Command {
var outfmt output.Format var outFmt output.Format
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "list", Use: "list",
Aliases: []string{"ls"}, Aliases: []string{"ls"},
@ -39,15 +39,15 @@ func newRepoListCmd(out io.Writer) *cobra.Command {
ValidArgsFunction: noCompletions, ValidArgsFunction: noCompletions,
RunE: func(_ *cobra.Command, _ []string) error { RunE: func(_ *cobra.Command, _ []string) error {
f, _ := repo.LoadFile(settings.RepositoryConfig) f, _ := repo.LoadFile(settings.RepositoryConfig)
if len(f.Repositories) == 0 && !(outfmt == output.JSON || outfmt == output.YAML) { if len(f.Repositories) == 0 && !(outFmt == output.JSON || outFmt == output.YAML) {
return errors.New("no repositories to show") return errors.New("no repositories to show")
} }
return outfmt.Write(out, &repoListWriter{f.Repositories}) return outFmt.Write(out, &repoListWriter{f.Repositories})
}, },
} }
bindOutputFlag(cmd, &outfmt) bindOutputFlag(cmd, &outFmt)
return cmd return cmd
} }
@ -80,17 +80,17 @@ func (r *repoListWriter) WriteYAML(out io.Writer) error {
func (r *repoListWriter) encodeByFormat(out io.Writer, format output.Format) error { func (r *repoListWriter) encodeByFormat(out io.Writer, format output.Format) error {
// Initialize the array so no results returns an empty array instead of null // Initialize the array so no results returns an empty array instead of null
repolist := make([]repositoryElement, 0, len(r.repos)) repoList := make([]repositoryElement, 0, len(r.repos))
for _, re := range r.repos { for _, re := range r.repos {
repolist = append(repolist, repositoryElement{Name: re.Name, URL: re.URL}) repoList = append(repoList, repositoryElement{Name: re.Name, URL: re.URL})
} }
switch format { switch format {
case output.JSON: case output.JSON:
return output.EncodeJSON(out, repolist) return output.EncodeJSON(out, repoList)
case output.YAML: case output.YAML:
return output.EncodeYAML(out, repolist) return output.EncodeYAML(out, repoList)
} }
// Because this is a non-exported function and only called internally by // Because this is a non-exported function and only called internally by
@ -113,9 +113,9 @@ func filterRepos(repos []*repo.Entry, ignoredRepoNames []string) []*repo.Entry {
ignored[repoName] = true ignored[repoName] = true
} }
for _, repo := range repos { for _, rp := range repos {
if _, removed := ignored[repo.Name]; !removed { if _, removed := ignored[rp.Name]; !removed {
filteredRepos = append(filteredRepos, repo) filteredRepos = append(filteredRepos, rp)
} }
} }
@ -129,8 +129,8 @@ func compListRepos(_ string, ignoredRepoNames []string) []string {
f, err := repo.LoadFile(settings.RepositoryConfig) f, err := repo.LoadFile(settings.RepositoryConfig)
if err == nil && len(f.Repositories) > 0 { if err == nil && len(f.Repositories) > 0 {
filteredRepos := filterRepos(f.Repositories, ignoredRepoNames) filteredRepos := filterRepos(f.Repositories, ignoredRepoNames)
for _, repo := range filteredRepos { for _, rp := range filteredRepos {
rNames = append(rNames, fmt.Sprintf("%s\t%s", repo.Name, repo.URL)) rNames = append(rNames, fmt.Sprintf("%s\t%s", rp.Name, rp.URL))
} }
} }
return rNames return rNames

@ -74,7 +74,7 @@ func (o *repoRemoveOptions) run(out io.Writer) error {
if err := removeRepoCache(o.repoCache, name); err != nil { if err := removeRepoCache(o.repoCache, name); err != nil {
return err return err
} }
fmt.Fprintf(out, "%q has been removed from your repositories\n", name) _, _ = fmt.Fprintf(out, "%q has been removed from your repositories\n", name)
} }
return nil return nil
@ -83,7 +83,7 @@ func (o *repoRemoveOptions) run(out io.Writer) error {
func removeRepoCache(root, name string) error { func removeRepoCache(root, name string) error {
idx := filepath.Join(root, helmpath.CacheChartsFile(name)) idx := filepath.Join(root, helmpath.CacheChartsFile(name))
if _, err := os.Stat(idx); err == nil { if _, err := os.Stat(idx); err == nil {
os.Remove(idx) _ = os.Remove(idx)
} }
idx = filepath.Join(root, helmpath.CacheIndexFile(name)) idx = filepath.Join(root, helmpath.CacheIndexFile(name))

@ -115,7 +115,7 @@ func (o *repoUpdateOptions) run(out io.Writer) error {
} }
func updateCharts(repos []*repo.ChartRepository, out io.Writer, failOnRepoUpdateFail bool) error { func updateCharts(repos []*repo.ChartRepository, out io.Writer, failOnRepoUpdateFail bool) error {
fmt.Fprintln(out, "Hang tight while we grab the latest from your chart repositories...") _, _ = fmt.Fprintln(out, "Hang tight while we grab the latest from your chart repositories...")
var wg sync.WaitGroup var wg sync.WaitGroup
var repoFailList []string var repoFailList []string
for _, re := range repos { for _, re := range repos {
@ -123,29 +123,29 @@ func updateCharts(repos []*repo.ChartRepository, out io.Writer, failOnRepoUpdate
go func(re *repo.ChartRepository) { go func(re *repo.ChartRepository) {
defer wg.Done() defer wg.Done()
if _, err := re.DownloadIndexFile(); err != nil { if _, err := re.DownloadIndexFile(); err != nil {
fmt.Fprintf(out, "...Unable to get an update from the %q chart repository (%s):\n\t%s\n", re.Config.Name, re.Config.URL, err) _, _ = fmt.Fprintf(out, "...Unable to get an update from the %q chart repository (%s):\n\t%s\n", re.Config.Name, re.Config.URL, err)
repoFailList = append(repoFailList, re.Config.URL) repoFailList = append(repoFailList, re.Config.URL)
} else { } else {
fmt.Fprintf(out, "...Successfully got an update from the %q chart repository\n", re.Config.Name) _, _ = fmt.Fprintf(out, "...Successfully got an update from the %q chart repository\n", re.Config.Name)
} }
}(re) }(re)
} }
wg.Wait() wg.Wait()
if len(repoFailList) > 0 && failOnRepoUpdateFail { if len(repoFailList) > 0 && failOnRepoUpdateFail {
return fmt.Errorf("Failed to update the following repositories: %s", return fmt.Errorf("failed to update the following repositories: %s",
repoFailList) repoFailList)
} }
fmt.Fprintln(out, "Update Complete. ⎈Happy Helming!⎈") _, _ = fmt.Fprintln(out, "Update Complete. ⎈Happy Helming!⎈")
return nil return nil
} }
func checkRequestedRepos(requestedRepos []string, validRepos []*repo.Entry) error { func checkRequestedRepos(requestedRepos []string, validRepos []*repo.Entry) error {
for _, requestedRepo := range requestedRepos { for _, requestedRepo := range requestedRepos {
found := false found := false
for _, repo := range validRepos { for _, validRepo := range validRepos {
if requestedRepo == repo.Name { if requestedRepo == validRepo.Name {
found = true found = true
break break
} }

@ -36,7 +36,7 @@ func TestUpdateCmd(t *testing.T) {
// The TestUpdateCharts test verifies the HTTP behavior independently. // The TestUpdateCharts test verifies the HTTP behavior independently.
updater := func(repos []*repo.ChartRepository, out io.Writer, _ bool) error { updater := func(repos []*repo.ChartRepository, out io.Writer, _ bool) error {
for _, re := range repos { for _, re := range repos {
fmt.Fprintln(out, re.Config.Name) _, _ = fmt.Fprintln(out, re.Config.Name)
} }
return nil return nil
} }
@ -61,7 +61,7 @@ func TestUpdateCmdMultiple(t *testing.T) {
// The TestUpdateCharts test verifies the HTTP behavior independently. // The TestUpdateCharts test verifies the HTTP behavior independently.
updater := func(repos []*repo.ChartRepository, out io.Writer, _ bool) error { updater := func(repos []*repo.ChartRepository, out io.Writer, _ bool) error {
for _, re := range repos { for _, re := range repos {
fmt.Fprintln(out, re.Config.Name) _, _ = fmt.Fprintln(out, re.Config.Name)
} }
return nil return nil
} }
@ -87,7 +87,7 @@ func TestUpdateCmdInvalid(t *testing.T) {
// The TestUpdateCharts test verifies the HTTP behavior independently. // The TestUpdateCharts test verifies the HTTP behavior independently.
updater := func(repos []*repo.ChartRepository, out io.Writer, _ bool) error { updater := func(repos []*repo.ChartRepository, out io.Writer, _ bool) error {
for _, re := range repos { for _, re := range repos {
fmt.Fprintln(out, re.Config.Name) _, _ = fmt.Fprintln(out, re.Config.Name)
} }
return nil return nil
} }
@ -104,7 +104,10 @@ 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) err := os.Mkdir(cachePath, os.ModePerm)
if err != nil {
t.Fatalf("error creating custom cache directory: %v", err)
}
ts, err := repotest.NewTempServerWithCleanup(t, "testdata/testserver/*.*") ts, err := repotest.NewTempServerWithCleanup(t, "testdata/testserver/*.*")
if err != nil { if err != nil {
@ -145,7 +148,7 @@ func TestUpdateCharts(t *testing.T) {
} }
b := bytes.NewBuffer(nil) b := bytes.NewBuffer(nil)
updateCharts([]*repo.ChartRepository{r}, b, false) _ = updateCharts([]*repo.ChartRepository{r}, b, false)
got := b.String() got := b.String()
if strings.Contains(got, "Unable to get an update") { if strings.Contains(got, "Unable to get an update") {

@ -70,7 +70,7 @@ func newRollbackCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
return err return err
} }
fmt.Fprintf(out, "Rollback was a success! Happy Helming!\n") _, _ = fmt.Fprintf(out, "Rollback was a success! Happy Helming!\n")
return nil return nil
}, },
} }

@ -134,8 +134,8 @@ func newRootCmd(actionConfig *action.Configuration, out io.Writer, args []string
loadingRules, loadingRules,
&clientcmd.ConfigOverrides{}).RawConfig(); err == nil { &clientcmd.ConfigOverrides{}).RawConfig(); err == nil {
comps := []string{} comps := []string{}
for name, context := range config.Contexts { for name, ctx := range config.Contexts {
comps = append(comps, fmt.Sprintf("%s\t%s", name, context.Cluster)) comps = append(comps, fmt.Sprintf("%s\t%s", name, ctx.Cluster))
} }
return comps, cobra.ShellCompDirectiveNoFileComp return comps, cobra.ShellCompDirectiveNoFileComp
} }
@ -151,7 +151,7 @@ func newRootCmd(actionConfig *action.Configuration, out io.Writer, args []string
// This call is required to gather configuration information prior to // This call is required to gather configuration information prior to
// execution. // execution.
flags.ParseErrorsWhitelist.UnknownFlags = true flags.ParseErrorsWhitelist.UnknownFlags = true
flags.Parse(args) _ = flags.Parse(args)
registryClient, err := newDefaultRegistryClient(false) registryClient, err := newDefaultRegistryClient(false)
if err != nil { if err != nil {
@ -210,7 +210,7 @@ func newRootCmd(actionConfig *action.Configuration, out io.Writer, args []string
return cmd, nil return cmd, nil
} }
func checkForExpiredRepos(repofile string) { func checkForExpiredRepos(repoPath string) {
expiredRepos := []struct { expiredRepos := []struct {
name string name string
@ -232,7 +232,7 @@ func checkForExpiredRepos(repofile string) {
// parse repo file. // parse repo file.
// Ignore the error because it is okay for a repo file to be unparseable at this // Ignore the error because it is okay for a repo file to be unparseable at this
// stage. Later checks will trap the error and respond accordingly. // stage. Later checks will trap the error and respond accordingly.
repoFile, err := repo.LoadFile(repofile) repoFile, err := repo.LoadFile(repoPath)
if err != nil { if err != nil {
return return
} }
@ -244,7 +244,7 @@ func checkForExpiredRepos(repofile string) {
} }
if url := r.URL; strings.Contains(url, exp.old) { if url := r.URL; strings.Contains(url, exp.old) {
fmt.Fprintf( _, _ = fmt.Fprintf(
os.Stderr, os.Stderr,
"WARNING: %q is deprecated for %q and will be deleted Nov. 13, 2020.\nWARNING: You should switch to %q via:\nWARNING: helm repo add %q %q --force-update\n", "WARNING: %q is deprecated for %q and will be deleted Nov. 13, 2020.\nWARNING: You should switch to %q via:\nWARNING: helm repo add %q %q --force-update\n",
exp.old, exp.old,
@ -258,9 +258,9 @@ func checkForExpiredRepos(repofile string) {
} }
func newRegistryClient(certFile, keyFile, caFile string, insecureSkipTLSverify, plainHTTP bool) (*registry.Client, error) { func newRegistryClient(certFile, keyFile, caFile string, insecureSkipTLSVerify, plainHTTP bool) (*registry.Client, error) {
if certFile != "" && keyFile != "" || caFile != "" || insecureSkipTLSverify { if certFile != "" && keyFile != "" || caFile != "" || insecureSkipTLSVerify {
registryClient, err := newRegistryClientWithTLS(certFile, keyFile, caFile, insecureSkipTLSverify) registryClient, err := newRegistryClientWithTLS(certFile, keyFile, caFile, insecureSkipTLSVerify)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -292,9 +292,9 @@ func newDefaultRegistryClient(plainHTTP bool) (*registry.Client, error) {
return registryClient, nil return registryClient, nil
} }
func newRegistryClientWithTLS(certFile, keyFile, caFile string, insecureSkipTLSverify bool) (*registry.Client, error) { func newRegistryClientWithTLS(certFile, keyFile, caFile string, insecureSkipTLSVerify bool) (*registry.Client, error) {
// Create a new registry client // Create a new registry client
registryClient, err := registry.NewRegistryClientWithTLS(os.Stderr, certFile, keyFile, caFile, insecureSkipTLSverify, registryClient, err := registry.NewRegistryClientWithTLS(os.Stderr, certFile, keyFile, caFile, insecureSkipTLSVerify,
settings.RegistryConfig, settings.Debug, settings.RegistryConfig, settings.Debug,
) )
if err != nil { if err != nil {

@ -25,10 +25,10 @@ import (
func TestSearchHubCmd(t *testing.T) { func TestSearchHubCmd(t *testing.T) {
// Setup a mock search service // Set up a mock search service
var searchResult = `{"data":[{"id":"stable/phpmyadmin","type":"chart","attributes":{"name":"phpmyadmin","repo":{"name":"stable","url":"https://charts.helm.sh/stable"},"description":"phpMyAdmin is an mysql administration frontend","home":"https://www.phpmyadmin.net/","keywords":["mariadb","mysql","phpmyadmin"],"maintainers":[{"name":"Bitnami","email":"containers@bitnami.com"}],"sources":["https://github.com/bitnami/bitnami-docker-phpmyadmin"],"icon":""},"links":{"self":"/v1/charts/stable/phpmyadmin"},"relationships":{"latestChartVersion":{"data":{"version":"3.0.0","app_version":"4.9.0-1","created":"2019-08-08T17:57:31.38Z","digest":"119c499251bffd4b06ff0cd5ac98c2ce32231f84899fb4825be6c2d90971c742","urls":["https://charts.helm.sh/stable/phpmyadmin-3.0.0.tgz"],"readme":"/v1/assets/stable/phpmyadmin/versions/3.0.0/README.md","values":"/v1/assets/stable/phpmyadmin/versions/3.0.0/values.yaml"},"links":{"self":"/v1/charts/stable/phpmyadmin/versions/3.0.0"}}}},{"id":"bitnami/phpmyadmin","type":"chart","attributes":{"name":"phpmyadmin","repo":{"name":"bitnami","url":"https://charts.bitnami.com"},"description":"phpMyAdmin is an mysql administration frontend","home":"https://www.phpmyadmin.net/","keywords":["mariadb","mysql","phpmyadmin"],"maintainers":[{"name":"Bitnami","email":"containers@bitnami.com"}],"sources":["https://github.com/bitnami/bitnami-docker-phpmyadmin"],"icon":""},"links":{"self":"/v1/charts/bitnami/phpmyadmin"},"relationships":{"latestChartVersion":{"data":{"version":"3.0.0","app_version":"4.9.0-1","created":"2019-08-08T18:34:13.341Z","digest":"66d77cf6d8c2b52c488d0a294cd4996bd5bad8dc41d3829c394498fb401c008a","urls":["https://charts.bitnami.com/bitnami/phpmyadmin-3.0.0.tgz"],"readme":"/v1/assets/bitnami/phpmyadmin/versions/3.0.0/README.md","values":"/v1/assets/bitnami/phpmyadmin/versions/3.0.0/values.yaml"},"links":{"self":"/v1/charts/bitnami/phpmyadmin/versions/3.0.0"}}}}]}` var searchResult = `{"data":[{"id":"stable/phpmyadmin","type":"chart","attributes":{"name":"phpmyadmin","repo":{"name":"stable","url":"https://charts.helm.sh/stable"},"description":"phpMyAdmin is an mysql administration frontend","home":"https://www.phpmyadmin.net/","keywords":["mariadb","mysql","phpmyadmin"],"maintainers":[{"name":"Bitnami","email":"containers@bitnami.com"}],"sources":["https://github.com/bitnami/bitnami-docker-phpmyadmin"],"icon":""},"links":{"self":"/v1/charts/stable/phpmyadmin"},"relationships":{"latestChartVersion":{"data":{"version":"3.0.0","app_version":"4.9.0-1","created":"2019-08-08T17:57:31.38Z","digest":"119c499251bffd4b06ff0cd5ac98c2ce32231f84899fb4825be6c2d90971c742","urls":["https://charts.helm.sh/stable/phpmyadmin-3.0.0.tgz"],"readme":"/v1/assets/stable/phpmyadmin/versions/3.0.0/README.md","values":"/v1/assets/stable/phpmyadmin/versions/3.0.0/values.yaml"},"links":{"self":"/v1/charts/stable/phpmyadmin/versions/3.0.0"}}}},{"id":"bitnami/phpmyadmin","type":"chart","attributes":{"name":"phpmyadmin","repo":{"name":"bitnami","url":"https://charts.bitnami.com"},"description":"phpMyAdmin is an mysql administration frontend","home":"https://www.phpmyadmin.net/","keywords":["mariadb","mysql","phpmyadmin"],"maintainers":[{"name":"Bitnami","email":"containers@bitnami.com"}],"sources":["https://github.com/bitnami/bitnami-docker-phpmyadmin"],"icon":""},"links":{"self":"/v1/charts/bitnami/phpmyadmin"},"relationships":{"latestChartVersion":{"data":{"version":"3.0.0","app_version":"4.9.0-1","created":"2019-08-08T18:34:13.341Z","digest":"66d77cf6d8c2b52c488d0a294cd4996bd5bad8dc41d3829c394498fb401c008a","urls":["https://charts.bitnami.com/bitnami/phpmyadmin-3.0.0.tgz"],"readme":"/v1/assets/bitnami/phpmyadmin/versions/3.0.0/README.md","values":"/v1/assets/bitnami/phpmyadmin/versions/3.0.0/values.yaml"},"links":{"self":"/v1/charts/bitnami/phpmyadmin/versions/3.0.0"}}}}]}`
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintln(w, searchResult) _, _ = fmt.Fprintln(w, searchResult)
})) }))
defer ts.Close() defer ts.Close()
@ -55,10 +55,10 @@ func TestSearchHubCmd(t *testing.T) {
func TestSearchHubListRepoCmd(t *testing.T) { func TestSearchHubListRepoCmd(t *testing.T) {
// Setup a mock search service // Set up a mock search service
var searchResult = `{"data":[{"id":"stable/phpmyadmin","type":"chart","attributes":{"name":"phpmyadmin","repo":{"name":"stable","url":"https://charts.helm.sh/stable"},"description":"phpMyAdmin is an mysql administration frontend","home":"https://www.phpmyadmin.net/","keywords":["mariadb","mysql","phpmyadmin"],"maintainers":[{"name":"Bitnami","email":"containers@bitnami.com"}],"sources":["https://github.com/bitnami/bitnami-docker-phpmyadmin"],"icon":""},"links":{"self":"/v1/charts/stable/phpmyadmin"},"relationships":{"latestChartVersion":{"data":{"version":"3.0.0","app_version":"4.9.0-1","created":"2019-08-08T17:57:31.38Z","digest":"119c499251bffd4b06ff0cd5ac98c2ce32231f84899fb4825be6c2d90971c742","urls":["https://charts.helm.sh/stable/phpmyadmin-3.0.0.tgz"],"readme":"/v1/assets/stable/phpmyadmin/versions/3.0.0/README.md","values":"/v1/assets/stable/phpmyadmin/versions/3.0.0/values.yaml"},"links":{"self":"/v1/charts/stable/phpmyadmin/versions/3.0.0"}}}},{"id":"bitnami/phpmyadmin","type":"chart","attributes":{"name":"phpmyadmin","repo":{"name":"bitnami","url":"https://charts.bitnami.com"},"description":"phpMyAdmin is an mysql administration frontend","home":"https://www.phpmyadmin.net/","keywords":["mariadb","mysql","phpmyadmin"],"maintainers":[{"name":"Bitnami","email":"containers@bitnami.com"}],"sources":["https://github.com/bitnami/bitnami-docker-phpmyadmin"],"icon":""},"links":{"self":"/v1/charts/bitnami/phpmyadmin"},"relationships":{"latestChartVersion":{"data":{"version":"3.0.0","app_version":"4.9.0-1","created":"2019-08-08T18:34:13.341Z","digest":"66d77cf6d8c2b52c488d0a294cd4996bd5bad8dc41d3829c394498fb401c008a","urls":["https://charts.bitnami.com/bitnami/phpmyadmin-3.0.0.tgz"],"readme":"/v1/assets/bitnami/phpmyadmin/versions/3.0.0/README.md","values":"/v1/assets/bitnami/phpmyadmin/versions/3.0.0/values.yaml"},"links":{"self":"/v1/charts/bitnami/phpmyadmin/versions/3.0.0"}}}}]}` var searchResult = `{"data":[{"id":"stable/phpmyadmin","type":"chart","attributes":{"name":"phpmyadmin","repo":{"name":"stable","url":"https://charts.helm.sh/stable"},"description":"phpMyAdmin is an mysql administration frontend","home":"https://www.phpmyadmin.net/","keywords":["mariadb","mysql","phpmyadmin"],"maintainers":[{"name":"Bitnami","email":"containers@bitnami.com"}],"sources":["https://github.com/bitnami/bitnami-docker-phpmyadmin"],"icon":""},"links":{"self":"/v1/charts/stable/phpmyadmin"},"relationships":{"latestChartVersion":{"data":{"version":"3.0.0","app_version":"4.9.0-1","created":"2019-08-08T17:57:31.38Z","digest":"119c499251bffd4b06ff0cd5ac98c2ce32231f84899fb4825be6c2d90971c742","urls":["https://charts.helm.sh/stable/phpmyadmin-3.0.0.tgz"],"readme":"/v1/assets/stable/phpmyadmin/versions/3.0.0/README.md","values":"/v1/assets/stable/phpmyadmin/versions/3.0.0/values.yaml"},"links":{"self":"/v1/charts/stable/phpmyadmin/versions/3.0.0"}}}},{"id":"bitnami/phpmyadmin","type":"chart","attributes":{"name":"phpmyadmin","repo":{"name":"bitnami","url":"https://charts.bitnami.com"},"description":"phpMyAdmin is an mysql administration frontend","home":"https://www.phpmyadmin.net/","keywords":["mariadb","mysql","phpmyadmin"],"maintainers":[{"name":"Bitnami","email":"containers@bitnami.com"}],"sources":["https://github.com/bitnami/bitnami-docker-phpmyadmin"],"icon":""},"links":{"self":"/v1/charts/bitnami/phpmyadmin"},"relationships":{"latestChartVersion":{"data":{"version":"3.0.0","app_version":"4.9.0-1","created":"2019-08-08T18:34:13.341Z","digest":"66d77cf6d8c2b52c488d0a294cd4996bd5bad8dc41d3829c394498fb401c008a","urls":["https://charts.bitnami.com/bitnami/phpmyadmin-3.0.0.tgz"],"readme":"/v1/assets/bitnami/phpmyadmin/versions/3.0.0/README.md","values":"/v1/assets/bitnami/phpmyadmin/versions/3.0.0/values.yaml"},"links":{"self":"/v1/charts/bitnami/phpmyadmin/versions/3.0.0"}}}}]}`
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintln(w, searchResult) _, _ = fmt.Fprintln(w, searchResult)
})) }))
defer ts.Close() defer ts.Close()
@ -154,9 +154,9 @@ func TestSearchHubCmd_FailOnNoResponseTests(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
// Setup a mock search service // Set up a mock search service
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintln(w, tt.response) _, _ = fmt.Fprintln(w, tt.response)
})) }))
defer ts.Close() defer ts.Close()

@ -92,7 +92,7 @@ func newShowCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
if err != nil { if err != nil {
return err return err
} }
fmt.Fprint(out, output) _, _ = fmt.Fprint(out, output)
return nil return nil
}, },
} }
@ -113,7 +113,7 @@ func newShowCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
if err != nil { if err != nil {
return err return err
} }
fmt.Fprint(out, output) _, _ = fmt.Fprint(out, output)
return nil return nil
}, },
} }
@ -134,7 +134,7 @@ func newShowCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
if err != nil { if err != nil {
return err return err
} }
fmt.Fprint(out, output) _, _ = fmt.Fprint(out, output)
return nil return nil
}, },
} }
@ -155,7 +155,7 @@ func newShowCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
if err != nil { if err != nil {
return err return err
} }
fmt.Fprint(out, output) _, _ = fmt.Fprint(out, output)
return nil return nil
}, },
} }
@ -176,7 +176,7 @@ func newShowCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
if err != nil { if err != nil {
return err return err
} }
fmt.Fprint(out, output) _, _ = fmt.Fprint(out, output)
return nil return nil
}, },
} }
@ -227,7 +227,7 @@ func runShow(args []string, client *action.Show) (string, error) {
func addRegistryClient(client *action.Show) error { func addRegistryClient(client *action.Show) error {
registryClient, err := newRegistryClient(client.CertFile, client.KeyFile, client.CaFile, registryClient, err := newRegistryClient(client.CertFile, client.KeyFile, client.CaFile,
client.InsecureSkipTLSverify, client.PlainHTTP) client.InsecureSkipTLSVerify, client.PlainHTTP)
if err != nil { if err != nil {
return fmt.Errorf("missing registry client: %w", err) return fmt.Errorf("missing registry client: %w", err)
} }

@ -51,7 +51,7 @@ The status consists of:
func newStatusCmd(cfg *action.Configuration, out io.Writer) *cobra.Command { func newStatusCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
client := action.NewStatus(cfg) client := action.NewStatus(cfg)
var outfmt output.Format var outFmt output.Format
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "status RELEASE_NAME", Use: "status RELEASE_NAME",
@ -69,7 +69,7 @@ func newStatusCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
// When the output format is a table the resources should be fetched // When the output format is a table the resources should be fetched
// and displayed as a table. When YAML or JSON the resources will be // and displayed as a table. When YAML or JSON the resources will be
// returned. This mirrors the handling in kubectl. // returned. This mirrors the handling in kubectl.
if outfmt == output.Table { if outFmt == output.Table {
client.ShowResourcesTable = true client.ShowResourcesTable = true
} }
rel, err := client.Run(args[0]) rel, err := client.Run(args[0])
@ -80,7 +80,7 @@ func newStatusCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
// strip chart metadata from the output // strip chart metadata from the output
rel.Chart = nil rel.Chart = nil
return outfmt.Write(out, &statusPrinter{rel, false, client.ShowDescription, client.ShowResources, false, false}) return outFmt.Write(out, &statusPrinter{rel, false, client.ShowDescription, client.ShowResources, false, false})
}, },
} }
@ -99,7 +99,7 @@ func newStatusCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
log.Fatal(err) log.Fatal(err)
} }
bindOutputFlag(cmd, &outfmt) bindOutputFlag(cmd, &outFmt)
f.BoolVar(&client.ShowDescription, "show-desc", false, "if set, display the description message of the named release") f.BoolVar(&client.ShowDescription, "show-desc", false, "if set, display the description message of the named release")
f.BoolVar(&client.ShowResources, "show-resources", false, "if set, display the resources of the named release") f.BoolVar(&client.ShowResources, "show-resources", false, "if set, display the resources of the named release")
@ -222,7 +222,7 @@ func (s statusPrinter) WriteTable(out io.Writer) error {
// Hide notes from output - option in install and upgrades // Hide notes from output - option in install and upgrades
if !s.hideNotes && len(s.release.Info.Notes) > 0 { if !s.hideNotes && len(s.release.Info.Notes) > 0 {
fmt.Fprintf(out, "NOTES:\n%s\n", strings.TrimSpace(s.release.Info.Notes)) _, _ = fmt.Fprintf(out, "NOTES:\n%s\n", strings.TrimSpace(s.release.Info.Notes))
} }
return nil return nil
} }

@ -74,7 +74,7 @@ func newTemplateCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
} }
registryClient, err := newRegistryClient(client.CertFile, client.KeyFile, client.CaFile, registryClient, err := newRegistryClient(client.CertFile, client.KeyFile, client.CaFile,
client.InsecureSkipTLSverify, client.PlainHTTP) client.InsecureSkipTLSVerify, client.PlainHTTP)
if err != nil { if err != nil {
return fmt.Errorf("missing registry client: %w", err) return fmt.Errorf("missing registry client: %w", err)
} }
@ -105,7 +105,7 @@ func newTemplateCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
// we always want to print the YAML, even if it is not valid. The error is still returned afterwards. // we always want to print the YAML, even if it is not valid. The error is still returned afterwards.
if rel != nil { if rel != nil {
var manifests bytes.Buffer var manifests bytes.Buffer
fmt.Fprintln(&manifests, strings.TrimSpace(rel.Manifest)) _, _ = fmt.Fprintln(&manifests, strings.TrimSpace(rel.Manifest))
if !client.DisableHooks { if !client.DisableHooks {
fileWritten := make(map[string]bool) fileWritten := make(map[string]bool)
for _, m := range rel.Hooks { for _, m := range rel.Hooks {
@ -113,7 +113,7 @@ func newTemplateCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
continue continue
} }
if client.OutputDir == "" { if client.OutputDir == "" {
fmt.Fprintf(&manifests, "---\n# Source: %s\n%s\n", m.Path, m.Manifest) _, _ = fmt.Fprintf(&manifests, "---\n# Source: %s\n%s\n", m.Path, m.Manifest)
} else { } else {
newDir := client.OutputDir newDir := client.OutputDir
if client.UseReleaseName { if client.UseReleaseName {
@ -178,10 +178,10 @@ func newTemplateCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
} }
} }
for _, m := range manifestsToRender { for _, m := range manifestsToRender {
fmt.Fprintf(out, "---\n%s\n", m) _, _ = fmt.Fprintf(out, "---\n%s\n", m)
} }
} else { } else {
fmt.Fprintf(out, "%s", manifests.String()) _, _ = fmt.Fprintf(out, "%s", manifests.String())
} }
} }

@ -62,10 +62,10 @@ func newUninstallCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
return err return err
} }
if res != nil && res.Info != "" { if res != nil && res.Info != "" {
fmt.Fprintln(out, res.Info) _, _ = fmt.Fprintln(out, res.Info)
} }
fmt.Fprintf(out, "release \"%s\" uninstalled\n", args[i]) _, _ = fmt.Fprintf(out, "release \"%s\" uninstalled\n", args[i])
} }
return nil return nil
}, },

@ -82,7 +82,7 @@ which can contain sensitive values. To hide Kubernetes Secrets use the
func newUpgradeCmd(cfg *action.Configuration, out io.Writer) *cobra.Command { func newUpgradeCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
client := action.NewUpgrade(cfg) client := action.NewUpgrade(cfg)
valueOpts := &values.Options{} valueOpts := &values.Options{}
var outfmt output.Format var outFmt output.Format
var createNamespace bool var createNamespace bool
cmd := &cobra.Command{ cmd := &cobra.Command{
@ -103,14 +103,14 @@ func newUpgradeCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
client.Namespace = settings.Namespace() client.Namespace = settings.Namespace()
registryClient, err := newRegistryClient(client.CertFile, client.KeyFile, client.CaFile, registryClient, err := newRegistryClient(client.CertFile, client.KeyFile, client.CaFile,
client.InsecureSkipTLSverify, client.PlainHTTP) client.InsecureSkipTLSVerify, client.PlainHTTP)
if err != nil { if err != nil {
return fmt.Errorf("missing registry client: %w", err) return fmt.Errorf("missing registry client: %w", err)
} }
client.SetRegistryClient(registryClient) client.SetRegistryClient(registryClient)
// This is for the case where "" is specifically passed in as a // This is for the case where "" is specifically passed in as a
// value. When there is no value passed in NoOptDefVal will be used // value. When there is no value passed in NoOptDefVal will be used,
// and it is set to client. See addInstallFlags. // and it is set to client. See addInstallFlags.
if client.DryRunOption == "" { if client.DryRunOption == "" {
client.DryRunOption = "none" client.DryRunOption = "none"
@ -122,10 +122,10 @@ func newUpgradeCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
histClient := action.NewHistory(cfg) histClient := action.NewHistory(cfg)
histClient.Max = 1 histClient.Max = 1
versions, err := histClient.Run(args[0]) versions, err := histClient.Run(args[0])
if err == driver.ErrReleaseNotFound || isReleaseUninstalled(versions) { if errors.Is(err, driver.ErrReleaseNotFound) || isReleaseUninstalled(versions) {
// Only print this to stdout for table output // Only print this to stdout for table output
if outfmt == output.Table { if outFmt == output.Table {
fmt.Fprintf(out, "Release %q does not exist. Installing it now.\n", args[0]) _, _ = fmt.Fprintf(out, "Release %q does not exist. Installing it now.\n", args[0])
} }
instClient := action.NewInstall(cfg) instClient := action.NewInstall(cfg)
instClient.CreateNamespace = createNamespace instClient.CreateNamespace = createNamespace
@ -159,7 +159,7 @@ func newUpgradeCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
if err != nil { if err != nil {
return err return err
} }
return outfmt.Write(out, &statusPrinter{rel, settings.Debug, false, false, false, instClient.HideNotes}) return outFmt.Write(out, &statusPrinter{rel, settings.Debug, false, false, false, instClient.HideNotes})
} else if err != nil { } else if err != nil {
return err return err
} }
@ -232,7 +232,7 @@ func newUpgradeCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
signal.Notify(cSignal, os.Interrupt, syscall.SIGTERM) signal.Notify(cSignal, os.Interrupt, syscall.SIGTERM)
go func() { go func() {
<-cSignal <-cSignal
fmt.Fprintf(out, "Release %s has been cancelled.\n", args[0]) _, _ = fmt.Fprintf(out, "Release %s has been cancelled.\n", args[0])
cancel() cancel()
}() }()
@ -242,11 +242,11 @@ func newUpgradeCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
return errors.Wrap(err, "UPGRADE FAILED") return errors.Wrap(err, "UPGRADE FAILED")
} }
if outfmt == output.Table { if outFmt == output.Table {
fmt.Fprintf(out, "Release %q has been upgraded. Happy Helming!\n", args[0]) _, _ = fmt.Fprintf(out, "Release %q has been upgraded. Happy Helming!\n", args[0])
} }
return outfmt.Write(out, &statusPrinter{rel, settings.Debug, false, false, false, client.HideNotes}) return outFmt.Write(out, &statusPrinter{rel, settings.Debug, false, false, false, client.HideNotes})
}, },
} }
@ -258,7 +258,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.Lookup("dry-run").NoOptDefVal = "client" f.Lookup("dry-run").NoOptDefVal = "client"
f.BoolVar(&client.Recreate, "recreate-pods", false, "performs pods restart for the resource if applicable") f.BoolVar(&client.Recreate, "recreate-pods", false, "performs pods restart for the resource if applicable")
f.MarkDeprecated("recreate-pods", "functionality will no longer be updated. Consult the documentation for other methods to recreate pods") _ = f.MarkDeprecated("recreate-pods", "functionality will no longer be updated. Consult the documentation for other methods to recreate pods")
f.BoolVar(&client.Force, "force", false, "force resource updates through a replacement strategy") f.BoolVar(&client.Force, "force", false, "force resource updates through a replacement strategy")
f.BoolVar(&client.DisableHooks, "no-hooks", false, "disable pre/post upgrade hooks") f.BoolVar(&client.DisableHooks, "no-hooks", false, "disable pre/post upgrade hooks")
f.BoolVar(&client.DisableOpenAPIValidation, "disable-openapi-validation", false, "if set, the upgrade process will not validate rendered templates against the Kubernetes OpenAPI Schema") f.BoolVar(&client.DisableOpenAPIValidation, "disable-openapi-validation", false, "if set, the upgrade process will not validate rendered templates against the Kubernetes OpenAPI Schema")
@ -280,7 +280,7 @@ func newUpgradeCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
f.BoolVar(&client.EnableDNS, "enable-dns", false, "enable DNS lookups when rendering templates") f.BoolVar(&client.EnableDNS, "enable-dns", false, "enable DNS lookups when rendering templates")
addChartPathOptionsFlags(f, &client.ChartPathOptions) addChartPathOptionsFlags(f, &client.ChartPathOptions)
addValueOptionsFlags(f, valueOpts) addValueOptionsFlags(f, valueOpts)
bindOutputFlag(cmd, &outfmt) bindOutputFlag(cmd, &outFmt)
bindPostRenderFlag(cmd, &client.PostRenderer) bindPostRenderFlag(cmd, &client.PostRenderer)
err := cmd.RegisterFlagCompletionFunc("version", func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { err := cmd.RegisterFlagCompletionFunc("version", func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {

@ -58,7 +58,7 @@ func newVerifyCmd(out io.Writer) *cobra.Command {
return err return err
} }
fmt.Fprint(out, client.Out) _, _ = fmt.Fprint(out, client.Out)
return nil return nil
}, },

@ -74,7 +74,7 @@ func newVersionCmd(out io.Writer) *cobra.Command {
f.BoolVar(&o.short, "short", false, "print the version number") f.BoolVar(&o.short, "short", false, "print the version number")
f.StringVar(&o.template, "template", "", "template for version string format") f.StringVar(&o.template, "template", "", "template for version string format")
f.BoolP("client", "c", true, "display client version information") f.BoolP("client", "c", true, "display client version information")
f.MarkHidden("client") _ = f.MarkHidden("client")
return cmd return cmd
} }
@ -87,7 +87,7 @@ func (o *versionOptions) run(out io.Writer) error {
} }
return tt.Execute(out, version.Get()) return tt.Execute(out, version.Get())
} }
fmt.Fprintln(out, formatVersion(o.short)) _, _ = fmt.Fprintln(out, formatVersion(o.short))
return nil return nil
} }

@ -29,7 +29,7 @@ var searchResult = `{"data":[{"id":"stable/phpmyadmin","type":"chart","attribute
func TestSearch(t *testing.T) { func TestSearch(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintln(w, searchResult) _, _ = fmt.Fprintln(w, searchResult)
})) }))
defer ts.Close() defer ts.Close()

@ -176,7 +176,7 @@ func (cfg *Configuration) renderResources(ch *chart.Chart, values chartutil.Valu
if strings.TrimSpace(content) == "" { if strings.TrimSpace(content) == "" {
continue continue
} }
fmt.Fprintf(b, "---\n# Source: %s\n%s\n", name, content) _, _ = fmt.Fprintf(b, "---\n# Source: %s\n%s\n", name, content)
} }
return hs, b, "", err return hs, b, "", err
} }
@ -187,7 +187,7 @@ func (cfg *Configuration) renderResources(ch *chart.Chart, values chartutil.Valu
if includeCrds { if includeCrds {
for _, crd := range ch.CRDObjects() { for _, crd := range ch.CRDObjects() {
if outputDir == "" { if outputDir == "" {
fmt.Fprintf(b, "---\n# Source: %s\n%s\n", crd.Filename, string(crd.File.Data[:])) _, _ = fmt.Fprintf(b, "---\n# Source: %s\n%s\n", crd.Filename, string(crd.File.Data[:]))
} else { } else {
err = writeToFile(outputDir, crd.Filename, string(crd.File.Data[:]), fileWritten[crd.Filename]) err = writeToFile(outputDir, crd.Filename, string(crd.File.Data[:]), fileWritten[crd.Filename])
if err != nil { if err != nil {
@ -201,9 +201,9 @@ func (cfg *Configuration) renderResources(ch *chart.Chart, values chartutil.Valu
for _, m := range manifests { for _, m := range manifests {
if outputDir == "" { if outputDir == "" {
if hideSecret && m.Head.Kind == "Secret" && m.Head.Version == "v1" { if hideSecret && m.Head.Kind == "Secret" && m.Head.Version == "v1" {
fmt.Fprintf(b, "---\n# Source: %s\n# HIDDEN: The Secret output has been suppressed\n", m.Name) _, _ = fmt.Fprintf(b, "---\n# Source: %s\n# HIDDEN: The Secret output has been suppressed\n", m.Name)
} else { } else {
fmt.Fprintf(b, "---\n# Source: %s\n%s\n", m.Name, m.Content) _, _ = fmt.Fprintf(b, "---\n# Source: %s\n%s\n", m.Name, m.Content)
} }
} else { } else {
newDir := outputDir newDir := outputDir
@ -359,7 +359,7 @@ func GetVersionSet(client discovery.ServerResourcesInterface) (chartutil.Version
versions = append(versions, k) versions = append(versions, k)
} }
return chartutil.VersionSet(versions), nil return versions, nil
} }
// recordRelease with an update operation in case reuse has been set. // recordRelease with an update operation in case reuse has been set.
@ -374,7 +374,7 @@ func (cfg *Configuration) Init(getter genericclioptions.RESTClientGetter, namesp
kc := kube.New(getter) kc := kube.New(getter)
kc.Log = log kc.Log = log
lazyClient := &lazyClient{ lazyCli := &lazyClient{
namespace: namespace, namespace: namespace,
clientFn: kc.Factory.KubernetesClientSet, clientFn: kc.Factory.KubernetesClientSet,
} }
@ -382,11 +382,11 @@ func (cfg *Configuration) Init(getter genericclioptions.RESTClientGetter, namesp
var store *storage.Storage var store *storage.Storage
switch helmDriver { switch helmDriver {
case "secret", "secrets", "": case "secret", "secrets", "":
d := driver.NewSecrets(newSecretClient(lazyClient)) d := driver.NewSecrets(newSecretClient(lazyCli))
d.Log = log d.Log = log
store = storage.Init(d) store = storage.Init(d)
case "configmap", "configmaps": case "configmap", "configmaps":
d := driver.NewConfigMaps(newConfigMapClient(lazyClient)) d := driver.NewConfigMaps(newConfigMapClient(lazyCli))
d.Log = log d.Log = log
store = storage.Init(d) store = storage.Init(d)
case "memory": case "memory":

@ -55,12 +55,12 @@ func (d *Dependency) List(chartpath string, out io.Writer) error {
} }
if c.Metadata.Dependencies == nil { if c.Metadata.Dependencies == nil {
fmt.Fprintf(out, "WARNING: no dependencies at %s\n", filepath.Join(chartpath, "charts")) _, _ = fmt.Fprintf(out, "WARNING: no dependencies at %s\n", filepath.Join(chartpath, "charts"))
return nil return nil
} }
d.printDependencies(chartpath, out, c) d.printDependencies(chartpath, out, c)
fmt.Fprintln(out) _, _ = fmt.Fprintln(out)
d.printMissing(chartpath, out, c.Metadata.Dependencies) d.printMissing(chartpath, out, c.Metadata.Dependencies)
return nil return nil
} }
@ -189,7 +189,7 @@ func (d *Dependency) printDependencies(chartpath string, out io.Writer, c *chart
for _, row := range c.Metadata.Dependencies { for _, row := range c.Metadata.Dependencies {
table.AddRow(row.Name, row.Version, row.Repository, d.dependencyStatus(chartpath, row, c)) table.AddRow(row.Name, row.Version, row.Repository, d.dependencyStatus(chartpath, row, c))
} }
fmt.Fprintln(out, table) _, _ = fmt.Fprintln(out, table)
} }
// printMissing prints warnings about charts that are present on disk, but are // printMissing prints warnings about charts that are present on disk, but are
@ -198,14 +198,14 @@ func (d *Dependency) printMissing(chartpath string, out io.Writer, reqs []*chart
folder := filepath.Join(chartpath, "charts/*") folder := filepath.Join(chartpath, "charts/*")
files, err := filepath.Glob(folder) files, err := filepath.Glob(folder)
if err != nil { if err != nil {
fmt.Fprintln(out, err) _, _ = fmt.Fprintln(out, err)
return return
} }
for _, f := range files { for _, f := range files {
fi, err := os.Stat(f) fi, err := os.Stat(f)
if err != nil { if err != nil {
fmt.Fprintf(out, "Warning: %s\n", err) _, _ = fmt.Fprintf(out, "Warning: %s\n", err)
} }
// Skip anything that is not a directory and not a tgz file. // Skip anything that is not a directory and not a tgz file.
if !fi.IsDir() && filepath.Ext(f) != ".tgz" { if !fi.IsDir() && filepath.Ext(f) != ".tgz" {
@ -213,7 +213,7 @@ func (d *Dependency) printMissing(chartpath string, out io.Writer, reqs []*chart
} }
c, err := loader.Load(f) c, err := loader.Load(f)
if err != nil { if err != nil {
fmt.Fprintf(out, "WARNING: %q is not a chart.\n", f) _, _ = fmt.Fprintf(out, "WARNING: %q is not a chart.\n", f)
continue continue
} }
found := false found := false
@ -224,7 +224,7 @@ func (d *Dependency) printMissing(chartpath string, out io.Writer, reqs []*chart
} }
} }
if !found { if !found {
fmt.Fprintf(out, "WARNING: %q is not in Chart.yaml.\n", f) _, _ = fmt.Fprintf(out, "WARNING: %q is not in Chart.yaml.\n", f)
} }
} }
} }

@ -55,7 +55,7 @@ import (
"helm.sh/helm/v3/pkg/storage/driver" "helm.sh/helm/v3/pkg/storage/driver"
) )
// NOTESFILE_SUFFIX that we want to treat special. It goes through the templating engine // NOTESFILE_SUFFIX that we want to treat special. It goes through the templating engine,
// but it's not a yaml file (resource) hence can't have hooks, etc. And the user actually // but it's not a yaml file (resource) hence can't have hooks, etc. And the user actually
// wants to see this file after rendering in the status command. However, it must be a suffix // wants to see this file after rendering in the status command. However, it must be a suffix
// since there can be filepath in front of it. // since there can be filepath in front of it.
@ -75,7 +75,7 @@ type Install struct {
DryRun bool DryRun bool
DryRunOption string DryRunOption string
// HideSecret can be set to true when DryRun is enabled in order to hide // HideSecret can be set to true when DryRun is enabled in order to hide
// Kubernetes Secrets in the output. It cannot be used outside of DryRun. // Kubernetes Secrets in the output. It cannot be used outside DryRun.
HideSecret bool HideSecret bool
DisableHooks bool DisableHooks bool
Replace bool Replace bool
@ -110,7 +110,7 @@ type Install struct {
// OutputDir/<ReleaseName> // OutputDir/<ReleaseName>
UseReleaseName bool UseReleaseName bool
PostRenderer postrender.PostRenderer PostRenderer postrender.PostRenderer
// Lock to control raceconditions when the process receives a SIGTERM // Lock to control race conditions when the process receives a SIGTERM
Lock sync.Mutex Lock sync.Mutex
} }
@ -119,7 +119,7 @@ type ChartPathOptions struct {
CaFile string // --ca-file CaFile string // --ca-file
CertFile string // --cert-file CertFile string // --cert-file
KeyFile string // --key-file KeyFile string // --key-file
InsecureSkipTLSverify bool // --insecure-skip-verify InsecureSkipTLSVerify bool // --insecure-skip-verify
PlainHTTP bool // --plain-http PlainHTTP bool // --plain-http
Keyring string // --keyring Keyring string // --keyring
Password string // --password Password string // --password
@ -222,7 +222,7 @@ func (i *Install) Run(chrt *chart.Chart, vals map[string]interface{}) (*release.
return i.RunWithContext(ctx, chrt, vals) return i.RunWithContext(ctx, chrt, vals)
} }
// Run executes the installation with Context // RunWithContext executes the installation with Context
// //
// When the task is cancelled through ctx, the function returns and the install // When the task is cancelled through ctx, the function returns and the install
// proceeds in the background. // proceeds in the background.
@ -264,7 +264,7 @@ func (i *Install) RunWithContext(ctx context.Context, chrt *chart.Chart, vals ma
} }
if i.ClientOnly { if i.ClientOnly {
// Add mock objects in here so it doesn't use Kube API server // Add mock objects in here, so it doesn't use Kube API server
// NOTE(bacongobbler): used for `helm template` // NOTE(bacongobbler): used for `helm template`
i.cfg.Capabilities = chartutil.DefaultCapabilities.Copy() i.cfg.Capabilities = chartutil.DefaultCapabilities.Copy()
if i.KubeVersion != nil { if i.KubeVersion != nil {
@ -382,7 +382,7 @@ func (i *Install) RunWithContext(ctx context.Context, chrt *chart.Chart, vals ma
} }
} }
// If Replace is true, we need to supercede the last release. // If Replace is true, we need to supersede the last release.
if i.Replace { if i.Replace {
if err := i.replaceRelease(rel); err != nil { if err := i.replaceRelease(rel); err != nil {
return nil, err return nil, err
@ -504,7 +504,7 @@ func (i *Install) failRelease(rel *release.Release, err error) (*release.Release
} }
return rel, errors.Wrapf(err, "release %s failed, and has been uninstalled due to atomic being set", i.ReleaseName) return rel, errors.Wrapf(err, "release %s failed, and has been uninstalled due to atomic being set", i.ReleaseName)
} }
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
} }
@ -761,7 +761,7 @@ func (c *ChartPathOptions) LocateChart(name string, settings *cli.EnvSettings) (
Options: []getter.Option{ Options: []getter.Option{
getter.WithPassCredentialsAll(c.PassCredentialsAll), getter.WithPassCredentialsAll(c.PassCredentialsAll),
getter.WithTLSClientConfig(c.CertFile, c.KeyFile, c.CaFile), getter.WithTLSClientConfig(c.CertFile, c.KeyFile, c.CaFile),
getter.WithInsecureSkipVerifyTLS(c.InsecureSkipTLSverify), getter.WithInsecureSkipVerifyTLS(c.InsecureSkipTLSVerify),
getter.WithPlainHTTP(c.PlainHTTP), getter.WithPlainHTTP(c.PlainHTTP),
}, },
RepositoryConfig: settings.RepositoryConfig, RepositoryConfig: settings.RepositoryConfig,
@ -778,7 +778,7 @@ func (c *ChartPathOptions) LocateChart(name string, settings *cli.EnvSettings) (
} }
if c.RepoURL != "" { if c.RepoURL != "" {
chartURL, err := repo.FindChartInAuthAndTLSAndPassRepoURL(c.RepoURL, c.Username, c.Password, name, version, chartURL, err := repo.FindChartInAuthAndTLSAndPassRepoURL(c.RepoURL, c.Username, c.Password, name, version,
c.CertFile, c.KeyFile, c.CaFile, c.InsecureSkipTLSverify, c.PassCredentialsAll, getter.All(settings)) c.CertFile, c.KeyFile, c.CaFile, c.InsecureSkipTLSVerify, c.PassCredentialsAll, getter.All(settings))
if err != nil { if err != nil {
return "", err return "", err
} }
@ -816,9 +816,9 @@ func (c *ChartPathOptions) LocateChart(name string, settings *cli.EnvSettings) (
return "", err return "", err
} }
lname, err := filepath.Abs(filename) abs, err := filepath.Abs(filename)
if err != nil { if err != nil {
return filename, err return filename, err
} }
return lname, nil return abs, nil
} }

@ -89,7 +89,7 @@ func (p *Pull) Run(chartRef string) (string, error) {
getter.WithBasicAuth(p.Username, p.Password), getter.WithBasicAuth(p.Username, p.Password),
getter.WithPassCredentialsAll(p.PassCredentialsAll), getter.WithPassCredentialsAll(p.PassCredentialsAll),
getter.WithTLSClientConfig(p.CertFile, p.KeyFile, p.CaFile), getter.WithTLSClientConfig(p.CertFile, p.KeyFile, p.CaFile),
getter.WithInsecureSkipVerifyTLS(p.InsecureSkipTLSverify), getter.WithInsecureSkipVerifyTLS(p.InsecureSkipTLSVerify),
getter.WithPlainHTTP(p.PlainHTTP), getter.WithPlainHTTP(p.PlainHTTP),
}, },
RegistryClient: p.cfg.RegistryClient, RegistryClient: p.cfg.RegistryClient,
@ -122,7 +122,7 @@ func (p *Pull) Run(chartRef string) (string, error) {
} }
if p.RepoURL != "" { if p.RepoURL != "" {
chartURL, err := repo.FindChartInAuthAndTLSAndPassRepoURL(p.RepoURL, p.Username, p.Password, chartRef, p.Version, p.CertFile, p.KeyFile, p.CaFile, p.InsecureSkipTLSverify, p.PassCredentialsAll, getter.All(p.Settings)) chartURL, err := repo.FindChartInAuthAndTLSAndPassRepoURL(p.RepoURL, p.Username, p.Password, chartRef, p.Version, p.CertFile, p.KeyFile, p.CaFile, p.InsecureSkipTLSVerify, p.PassCredentialsAll, getter.All(p.Settings))
if err != nil { if err != nil {
return out.String(), err return out.String(), err
} }
@ -136,10 +136,10 @@ func (p *Pull) Run(chartRef string) (string, error) {
if p.Verify { if p.Verify {
for name := range v.SignedBy.Identities { for name := range v.SignedBy.Identities {
fmt.Fprintf(&out, "Signed by: %v\n", name) _, _ = fmt.Fprintf(&out, "Signed by: %v\n", name)
} }
fmt.Fprintf(&out, "Using Key With Fingerprint: %X\n", v.SignedBy.PrimaryKey.Fingerprint) _, _ = fmt.Fprintf(&out, "Using Key With Fingerprint: %X\n", v.SignedBy.PrimaryKey.Fingerprint)
fmt.Fprintf(&out, "Chart Hash Verified: %s\n", v.FileHash) _, _ = fmt.Fprintf(&out, "Chart Hash Verified: %s\n", v.FileHash)
} }
// After verification, untar the chart into the requested directory. // After verification, untar the chart into the requested directory.

@ -131,9 +131,9 @@ func (r *ReleaseTesting) GetPodLogs(out io.Writer, rel *release.Release) error {
return errors.Wrapf(err, "unable to get pod logs for %s", h.Name) return errors.Wrapf(err, "unable to get pod logs for %s", h.Name)
} }
fmt.Fprintf(out, "POD LOGS: %s\n", h.Name) _, _ = fmt.Fprintf(out, "POD LOGS: %s\n", h.Name)
_, err = io.Copy(out, logReader) _, err = io.Copy(out, logReader)
fmt.Fprintln(out) _, _ = fmt.Fprintln(out)
if err != nil { if err != nil {
return errors.Wrapf(err, "unable to write pod logs for %s", h.Name) return errors.Wrapf(err, "unable to write pod logs for %s", h.Name)
} }

@ -104,12 +104,12 @@ func (s *Show) Run(chartpath string) (string, error) {
var out strings.Builder var out strings.Builder
if s.OutputFormat == ShowChart || s.OutputFormat == ShowAll { if s.OutputFormat == ShowChart || s.OutputFormat == ShowAll {
fmt.Fprintf(&out, "%s\n", cf) _, _ = fmt.Fprintf(&out, "%s\n", cf)
} }
if (s.OutputFormat == ShowValues || s.OutputFormat == ShowAll) && s.chart.Values != nil { if (s.OutputFormat == ShowValues || s.OutputFormat == ShowAll) && s.chart.Values != nil {
if s.OutputFormat == ShowAll { if s.OutputFormat == ShowAll {
fmt.Fprintln(&out, "---") _, _ = fmt.Fprintln(&out, "---")
} }
if s.JSONPathTemplate != "" { if s.JSONPathTemplate != "" {
printer, err := printers.NewJSONPathPrinter(s.JSONPathTemplate) printer, err := printers.NewJSONPathPrinter(s.JSONPathTemplate)
@ -119,8 +119,8 @@ func (s *Show) Run(chartpath string) (string, error) {
printer.Execute(&out, s.chart.Values) printer.Execute(&out, s.chart.Values)
} else { } else {
for _, f := range s.chart.Raw { for _, f := range s.chart.Raw {
if f.Name == chartutil.ValuesfileName { if f.Name == chartutil.ValuesFileName {
fmt.Fprintln(&out, string(f.Data)) _, _ = fmt.Fprintln(&out, string(f.Data))
} }
} }
} }
@ -130,9 +130,9 @@ func (s *Show) Run(chartpath string) (string, error) {
readme := findReadme(s.chart.Files) readme := findReadme(s.chart.Files)
if readme != nil { if readme != nil {
if s.OutputFormat == ShowAll { if s.OutputFormat == ShowAll {
fmt.Fprintln(&out, "---") _, _ = fmt.Fprintln(&out, "---")
} }
fmt.Fprintf(&out, "%s\n", readme.Data) _, _ = fmt.Fprintf(&out, "%s\n", readme.Data)
} }
} }
@ -140,10 +140,10 @@ func (s *Show) Run(chartpath string) (string, error) {
crds := s.chart.CRDObjects() crds := s.chart.CRDObjects()
if len(crds) > 0 { if len(crds) > 0 {
if s.OutputFormat == ShowAll && !bytes.HasPrefix(crds[0].File.Data, []byte("---")) { if s.OutputFormat == ShowAll && !bytes.HasPrefix(crds[0].File.Data, []byte("---")) {
fmt.Fprintln(&out, "---") _, _ = fmt.Fprintln(&out, "---")
} }
for _, crd := range crds { for _, crd := range crds {
fmt.Fprintf(&out, "%s\n", string(crd.File.Data)) _, _ = fmt.Fprintf(&out, "%s\n", string(crd.File.Data))
} }
} }
} }

@ -111,7 +111,7 @@ type Upgrade struct {
DisableOpenAPIValidation bool DisableOpenAPIValidation bool
// Get missing dependencies // Get missing dependencies
DependencyUpdate bool DependencyUpdate bool
// Lock to control raceconditions when the process receives a SIGTERM // Lock to control race conditions when the process receives a SIGTERM
Lock sync.Mutex Lock sync.Mutex
// Enable DNS lookups when rendering templates // Enable DNS lookups when rendering templates
EnableDNS bool EnableDNS bool

@ -45,10 +45,10 @@ func (v *Verify) Run(chartfile string) error {
} }
for name := range p.SignedBy.Identities { for name := range p.SignedBy.Identities {
fmt.Fprintf(&out, "Signed by: %v\n", name) _, _ = fmt.Fprintf(&out, "Signed by: %v\n", name)
} }
fmt.Fprintf(&out, "Using Key With Fingerprint: %X\n", p.SignedBy.PrimaryKey.Fingerprint) _, _ = fmt.Fprintf(&out, "Using Key With Fingerprint: %X\n", p.SignedBy.PrimaryKey.Fingerprint)
fmt.Fprintf(&out, "Chart Hash Verified: %s\n", p.FileHash) _, _ = fmt.Fprintf(&out, "Chart Hash Verified: %s\n", p.FileHash)
// TODO(mattfarina): The output is set as a property rather than returned // TODO(mattfarina): The output is set as a property rather than returned
// to maintain the Go API. In Helm v4 this function should return the out // to maintain the Go API. In Helm v4 this function should return the out

@ -38,7 +38,7 @@ type Chart struct {
// This should not be used except in special cases like `helm show values`, // This should not be used except in special cases like `helm show values`,
// where we want to display the raw values, comments and all. // where we want to display the raw values, comments and all.
Raw []*File `json:"-"` Raw []*File `json:"-"`
// Metadata is the contents of the Chartfile. // Metadata is the contents of the ChartFile.
Metadata *Metadata `json:"metadata"` Metadata *Metadata `json:"metadata"`
// Lock is the contents of Chart.lock. // Lock is the contents of Chart.lock.
Lock *Lock `json:"lock"` Lock *Lock `json:"lock"`
@ -156,8 +156,8 @@ func (ch *Chart) CRDObjects() []CRD {
// Find all resources in the crds/ directory // Find all resources in the crds/ directory
for _, f := range ch.Files { for _, f := range ch.Files {
if strings.HasPrefix(f.Name, "crds/") && hasManifestExtension(f.Name) { if strings.HasPrefix(f.Name, "crds/") && hasManifestExtension(f.Name) {
mycrd := CRD{Name: f.Name, Filename: filepath.Join(ch.ChartFullPath(), f.Name), File: f} crd := CRD{Name: f.Name, Filename: filepath.Join(ch.ChartFullPath(), f.Name), File: f}
crds = append(crds, mycrd) crds = append(crds, crd)
} }
} }
// Get CRDs from dependencies, too. // Get CRDs from dependencies, too.
@ -167,7 +167,7 @@ func (ch *Chart) CRDObjects() []CRD {
return crds return crds
} }
func hasManifestExtension(fname string) bool { func hasManifestExtension(filename string) bool {
ext := filepath.Ext(fname) ext := filepath.Ext(filename)
return strings.EqualFold(ext, ".yaml") || strings.EqualFold(ext, ".yml") || strings.EqualFold(ext, ".json") return strings.EqualFold(ext, ".yaml") || strings.EqualFold(ext, ".yml") || strings.EqualFold(ext, ".json")
} }

@ -53,7 +53,7 @@ var (
type Capabilities struct { type Capabilities struct {
// KubeVersion is the Kubernetes version. // KubeVersion is the Kubernetes version.
KubeVersion KubeVersion KubeVersion KubeVersion
// APIversions are supported Kubernetes API versions. // APIVersions are supported Kubernetes API versions.
APIVersions VersionSet APIVersions VersionSet
// HelmVersion is the build information for this helm version // HelmVersion is the build information for this helm version
HelmVersion helmversion.BuildInfo HelmVersion helmversion.BuildInfo
@ -111,11 +111,11 @@ func (v VersionSet) Has(apiVersion string) bool {
} }
func allKnownVersions() VersionSet { 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) _ = apiextensionsv1beta1.AddToScheme(scheme.Scheme)
apiextensionsv1.AddToScheme(scheme.Scheme) _ = apiextensionsv1.AddToScheme(scheme.Scheme)
groups := scheme.Scheme.PrioritizedVersionsAllGroups() groups := scheme.Scheme.PrioritizedVersionsAllGroups()
vs := make(VersionSet, 0, len(groups)) vs := make(VersionSet, 0, len(groups))

@ -26,8 +26,8 @@ import (
"helm.sh/helm/v3/pkg/chart" "helm.sh/helm/v3/pkg/chart"
) )
// LoadChartfile loads a Chart.yaml file into a *chart.Metadata. // LoadChartFile loads a Chart.yaml file into a *chart.Metadata.
func LoadChartfile(filename string) (*chart.Metadata, error) { func LoadChartFile(filename string) (*chart.Metadata, error) {
b, err := os.ReadFile(filename) b, err := os.ReadFile(filename)
if err != nil { if err != nil {
return nil, err return nil, err
@ -37,10 +37,10 @@ func LoadChartfile(filename string) (*chart.Metadata, error) {
return y, err return y, err
} }
// SaveChartfile saves the given metadata as a Chart.yaml file at the given path. // SaveChartFile saves the given metadata as a Chart.yaml file at the given path.
// //
// 'filename' should be the complete path and filename ('foo/Chart.yaml') // 'filename' should be the complete path and filename ('foo/Chart.yaml')
func SaveChartfile(filename string, cf *chart.Metadata) error { func SaveChartFile(filename string, cf *chart.Metadata) error {
// Pull out the dependencies of a v1 Chart, since there's no way // Pull out the dependencies of a v1 Chart, since there's no way
// to tell the serializer to skip a field for just this use case // to tell the serializer to skip a field for just this use case
savedDependencies := cf.Dependencies savedDependencies := cf.Dependencies
@ -67,14 +67,14 @@ func IsChartDir(dirName string) (bool, error) {
return false, errors.Errorf("%q is not a directory", dirName) return false, errors.Errorf("%q is not a directory", dirName)
} }
chartYaml := filepath.Join(dirName, ChartfileName) chartYaml := filepath.Join(dirName, ChartFileName)
if _, err := os.Stat(chartYaml); os.IsNotExist(err) { if _, err := os.Stat(chartYaml); os.IsNotExist(err) {
return false, errors.Errorf("no %s exists in directory %q", ChartfileName, dirName) return false, errors.Errorf("no %s exists in directory %q", ChartFileName, dirName)
} }
chartYamlContent, err := os.ReadFile(chartYaml) chartYamlContent, err := os.ReadFile(chartYaml)
if err != nil { if err != nil {
return false, errors.Errorf("cannot read %s in directory %q", ChartfileName, dirName) return false, errors.Errorf("cannot read %s in directory %q", ChartFileName, dirName)
} }
chartContent := new(chart.Metadata) chartContent := new(chart.Metadata)
@ -82,10 +82,10 @@ func IsChartDir(dirName string) (bool, error) {
return false, err return false, err
} }
if chartContent == nil { if chartContent == nil {
return false, errors.Errorf("chart metadata (%s) missing", ChartfileName) return false, errors.Errorf("chart metadata (%s) missing", ChartFileName)
} }
if chartContent.Name == "" { if chartContent.Name == "" {
return false, errors.Errorf("invalid chart (%s): name must not be empty", ChartfileName) return false, errors.Errorf("invalid chart (%s): name must not be empty", ChartFileName)
} }
return true, nil return true, nil

@ -24,19 +24,19 @@ import (
const testfile = "testdata/chartfiletest.yaml" const testfile = "testdata/chartfiletest.yaml"
func TestLoadChartfile(t *testing.T) { func TestLoadChartFile(t *testing.T) {
f, err := LoadChartfile(testfile) f, err := LoadChartFile(testfile)
if err != nil { if err != nil {
t.Errorf("Failed to open %s: %s", testfile, err) t.Errorf("Failed to open %s: %s", testfile, err)
return return
} }
verifyChartfile(t, f, "frobnitz") verifyChartFile(t, f, "frobnitz")
} }
func verifyChartfile(t *testing.T, f *chart.Metadata, name string) { func verifyChartFile(t *testing.T, f *chart.Metadata, name string) {
if f == nil { //nolint:staticcheck if f == nil { //nolint:staticcheck
t.Fatal("Failed verifyChartfile because f is nil") t.Fatal("Failed verifyChartFile because f is nil")
} }
if f.APIVersion != chart.APIVersionV1 { //nolint:staticcheck if f.APIVersion != chart.APIVersionV1 { //nolint:staticcheck

@ -33,14 +33,14 @@ func concatPrefix(a, b string) string {
return fmt.Sprintf("%s.%s", a, b) return fmt.Sprintf("%s.%s", a, b)
} }
// CoalesceValues coalesces all of the values in a chart (and its subcharts). // CoalesceValues coalesces all the values in a chart (and its subcharts).
// //
// Values are coalesced together using the following rules: // Values are coalesced together using the following rules:
// //
// - Values in a higher level chart always override values in a lower-level // - Values in a higher level chart always override values in a lower-level
// dependency chart // dependency chart
// - Scalar values and arrays are replaced, maps are merged // - Scalar values and arrays are replaced, maps are merged
// - A chart has access to all of the variables for it, as well as all of // - A chart has access to all the variables for it, as well as all
// the values destined for its dependencies. // the values destined for its dependencies.
func CoalesceValues(chrt *chart.Chart, vals map[string]interface{}) (Values, error) { func CoalesceValues(chrt *chart.Chart, vals map[string]interface{}) (Values, error) {
valsCopy, err := copyValues(vals) valsCopy, err := copyValues(vals)
@ -58,7 +58,7 @@ func CoalesceValues(chrt *chart.Chart, vals map[string]interface{}) (Values, err
// - Values in a higher level chart always override values in a lower-level // - Values in a higher level chart always override values in a lower-level
// dependency chart // dependency chart
// - Scalar values and arrays are replaced, maps are merged // - Scalar values and arrays are replaced, maps are merged
// - A chart has access to all of the variables for it, as well as all of // - A chart has access to all the variables for it, as well as all
// the values destined for its dependencies. // the values destined for its dependencies.
// //
// Retaining Nils is useful when processes early in a Helm action or business // Retaining Nils is useful when processes early in a Helm action or business
@ -103,21 +103,21 @@ func coalesce(printf printFn, ch *chart.Chart, dest map[string]interface{}, pref
// coalesceDeps coalesces the dependencies of the given chart. // coalesceDeps coalesces the dependencies of the given chart.
func coalesceDeps(printf printFn, chrt *chart.Chart, dest map[string]interface{}, prefix string, merge bool) (map[string]interface{}, error) { func coalesceDeps(printf printFn, chrt *chart.Chart, dest map[string]interface{}, prefix string, merge bool) (map[string]interface{}, error) {
for _, subchart := range chrt.Dependencies() { for _, subChart := range chrt.Dependencies() {
if c, ok := dest[subchart.Name()]; !ok { if c, ok := dest[subChart.Name()]; !ok {
// If dest doesn't already have the key, create it. // If dest doesn't already have the key, create it.
dest[subchart.Name()] = make(map[string]interface{}) dest[subChart.Name()] = make(map[string]interface{})
} else if !istable(c) { } else if !isTable(c) {
return dest, errors.Errorf("type mismatch on %s: %t", subchart.Name(), c) return dest, errors.Errorf("type mismatch on %s: %t", subChart.Name(), c)
} }
if dv, ok := dest[subchart.Name()]; ok { if dv, ok := dest[subChart.Name()]; ok {
dvmap := dv.(map[string]interface{}) dvmap := dv.(map[string]interface{})
subPrefix := concatPrefix(prefix, chrt.Metadata.Name) subPrefix := concatPrefix(prefix, chrt.Metadata.Name)
// Get globals out of dest and merge them into dvmap. // Get globals out of dest and merge them into dvmap.
coalesceGlobals(printf, dvmap, dest, subPrefix, merge) coalesceGlobals(printf, dvmap, dest, subPrefix, merge)
// Now coalesce the rest of the values. // Now coalesce the rest of the values.
var err error var err error
dest[subchart.Name()], err = coalesce(printf, subchart, dvmap, subPrefix, merge) dest[subChart.Name()], err = coalesce(printf, subChart, dvmap, subPrefix, merge)
if err != nil { if err != nil {
return dest, err return dest, err
} }
@ -132,16 +132,16 @@ func coalesceDeps(printf printFn, chrt *chart.Chart, dest map[string]interface{}
func coalesceGlobals(printf printFn, dest, src map[string]interface{}, prefix string, _ bool) { func coalesceGlobals(printf printFn, dest, src map[string]interface{}, prefix string, _ bool) {
var dg, sg map[string]interface{} var dg, sg map[string]interface{}
if destglob, ok := dest[GlobalKey]; !ok { if destGlob, ok := dest[GlobalKey]; !ok {
dg = make(map[string]interface{}) dg = make(map[string]interface{})
} else if dg, ok = destglob.(map[string]interface{}); !ok { } else if dg, ok = destGlob.(map[string]interface{}); !ok {
printf("warning: skipping globals because destination %s is not a table.", GlobalKey) printf("warning: skipping globals because destination %s is not a table.", GlobalKey)
return return
} }
if srcglob, ok := src[GlobalKey]; !ok { if srcGlob, ok := src[GlobalKey]; !ok {
sg = make(map[string]interface{}) sg = make(map[string]interface{})
} else if sg, ok = srcglob.(map[string]interface{}); !ok { } else if sg, ok = srcGlob.(map[string]interface{}); !ok {
printf("warning: skipping globals because source %s is not a table.", GlobalKey) printf("warning: skipping globals because source %s is not a table.", GlobalKey)
return return
} }
@ -151,7 +151,7 @@ func coalesceGlobals(printf printFn, dest, src map[string]interface{}, prefix st
// here, but I haven't found a way. So for the time being, let's allow // here, but I haven't found a way. So for the time being, let's allow
// tables in globals. // tables in globals.
for key, val := range sg { for key, val := range sg {
if istable(val) { if isTable(val) {
vv := copyMap(val.(map[string]interface{})) vv := copyMap(val.(map[string]interface{}))
if destv, ok := dg[key]; !ok { if destv, ok := dg[key]; !ok {
// Here there is no merge. We're just adding. // Here there is no merge. We're just adding.
@ -170,7 +170,7 @@ func coalesceGlobals(printf printFn, dest, src map[string]interface{}, prefix st
dg[key] = vv dg[key] = vv
} }
} }
} else if dv, ok := dg[key]; ok && istable(dv) { } else if dv, ok := dg[key]; ok && isTable(dv) {
// It's not clear if this condition can actually ever trigger. // It's not clear if this condition can actually ever trigger.
printf("key %s is table. Skipping", key) printf("key %s is table. Skipping", key)
} else { } else {
@ -279,13 +279,13 @@ func coalesceTablesFullKey(printf printFn, dst, src map[string]interface{}, pref
delete(dst, key) delete(dst, key)
} else if !ok { } else if !ok {
dst[key] = val dst[key] = val
} else if istable(val) { } else if isTable(val) {
if istable(dv) { if isTable(dv) {
coalesceTablesFullKey(printf, dv.(map[string]interface{}), val.(map[string]interface{}), fullkey, merge) coalesceTablesFullKey(printf, dv.(map[string]interface{}), val.(map[string]interface{}), fullkey, merge)
} else { } else {
printf("warning: cannot overwrite table with non table for %s (%v)", fullkey, val) printf("warning: cannot overwrite table with non table for %s (%v)", fullkey, val)
} }
} else if istable(dv) && val != nil { } else if isTable(dv) && val != nil {
printf("warning: destination for %s is a table. Ignoring non-table value (%v)", fullkey, val) printf("warning: destination for %s is a table. Ignoring non-table value (%v)", fullkey, val)
} }
} }

@ -38,20 +38,20 @@ import (
var chartName = regexp.MustCompile("^[a-zA-Z0-9._-]+$") var chartName = regexp.MustCompile("^[a-zA-Z0-9._-]+$")
const ( const (
// ChartfileName is the default Chart file name. // ChartFileName is the default Chart file name.
ChartfileName = "Chart.yaml" ChartFileName = "Chart.yaml"
// ValuesfileName is the default values file name. // ValuesFileName is the default values file name.
ValuesfileName = "values.yaml" ValuesFileName = "values.yaml"
// SchemafileName is the default values schema file name. // SchemaFileName is the default values schema file name.
SchemafileName = "values.schema.json" SchemaFileName = "values.schema.json"
// TemplatesDir is the relative directory name for templates. // TemplatesDir is the relative directory name for templates.
TemplatesDir = "templates" TemplatesDir = "templates"
// ChartsDir is the relative directory name for charts dependencies. // ChartsDir is the relative directory name for charts dependencies.
ChartsDir = "charts" ChartsDir = "charts"
// TemplatesTestsDir is the relative directory name for tests. // TemplatesTestsDir is the relative directory name for tests.
TemplatesTestsDir = TemplatesDir + sep + "tests" TemplatesTestsDir = TemplatesDir + sep + "tests"
// IgnorefileName is the name of the Helm ignore file. // IgnoreFileName is the name of the Helm ignore file.
IgnorefileName = ".helmignore" IgnoreFileName = ".helmignore"
// IngressFileName is the name of the example ingress file. // IngressFileName is the name of the example ingress file.
IngressFileName = TemplatesDir + sep + "ingress.yaml" IngressFileName = TemplatesDir + sep + "ingress.yaml"
// DeploymentName is the name of the example deployment file. // DeploymentName is the name of the example deployment file.
@ -76,7 +76,7 @@ const maxChartNameLength = 250
const sep = string(filepath.Separator) const sep = string(filepath.Separator)
const defaultChartfile = `apiVersion: v2 const defaultChartFile = `apiVersion: v2
name: %s name: %s
description: A Helm chart for Kubernetes description: A Helm chart for Kubernetes
@ -578,7 +578,7 @@ func CreateFrom(chartfile *chart.Metadata, dest, src string) error {
// key in order to preserve the comments in the YAML. The name placeholder // key in order to preserve the comments in the YAML. The name placeholder
// needs to be replaced on that file. // needs to be replaced on that file.
for _, f := range schart.Raw { for _, f := range schart.Raw {
if f.Name == ValuesfileName { if f.Name == ValuesFileName {
f.Data = transform(string(f.Data), schart.Name()) f.Data = transform(string(f.Data), schart.Name())
} }
} }
@ -628,17 +628,17 @@ func Create(name, dir string) (string, error) {
}{ }{
{ {
// Chart.yaml // Chart.yaml
path: filepath.Join(cdir, ChartfileName), path: filepath.Join(cdir, ChartFileName),
content: []byte(fmt.Sprintf(defaultChartfile, name)), content: []byte(fmt.Sprintf(defaultChartFile, name)),
}, },
{ {
// values.yaml // values.yaml
path: filepath.Join(cdir, ValuesfileName), path: filepath.Join(cdir, ValuesFileName),
content: []byte(fmt.Sprintf(defaultValues, name)), content: []byte(fmt.Sprintf(defaultValues, name)),
}, },
{ {
// .helmignore // .helmignore
path: filepath.Join(cdir, IgnorefileName), path: filepath.Join(cdir, IgnoreFileName),
content: []byte(defaultIgnore), content: []byte(defaultIgnore),
}, },
{ {
@ -686,7 +686,7 @@ func Create(name, dir string) (string, error) {
for _, file := range files { for _, file := range files {
if _, err := os.Stat(file.path); err == nil { if _, err := os.Stat(file.path); err == nil {
// There is no handle to a preferred output stream here. // There is no handle to a preferred output stream here.
fmt.Fprintf(Stderr, "WARNING: File %q already exists. Overwriting.\n", file.path) _, _ = fmt.Fprintf(Stderr, "WARNING: File %q already exists. Overwriting.\n", file.path)
} }
if err := writeFile(file.path, file.content); err != nil { if err := writeFile(file.path, file.content); err != nil {
return cdir, err return cdir, err

@ -46,17 +46,17 @@ func TestCreate(t *testing.T) {
} }
for _, f := range []string{ for _, f := range []string{
ChartfileName, ChartFileName,
DeploymentName, DeploymentName,
HelpersName, HelpersName,
IgnorefileName, IgnoreFileName,
NotesName, NotesName,
ServiceAccountName, ServiceAccountName,
ServiceName, ServiceName,
TemplatesDir, TemplatesDir,
TemplatesTestsDir, TemplatesTestsDir,
TestConnectionName, TestConnectionName,
ValuesfileName, ValuesFileName,
} { } {
if _, err := os.Stat(filepath.Join(dir, f)); err != nil { if _, err := os.Stat(filepath.Join(dir, f)); err != nil {
t.Errorf("Expected %s file: %s", f, err) t.Errorf("Expected %s file: %s", f, err)
@ -90,8 +90,8 @@ func TestCreateFrom(t *testing.T) {
} }
for _, f := range []string{ for _, f := range []string{
ChartfileName, ChartFileName,
ValuesfileName, ValuesFileName,
filepath.Join(TemplatesDir, "placeholder.tpl"), filepath.Join(TemplatesDir, "placeholder.tpl"),
} { } {
if _, err := os.Stat(filepath.Join(dir, f)); err != nil { if _, err := os.Stat(filepath.Join(dir, f)); err != nil {

@ -335,7 +335,7 @@ func trimNilValues(vals map[string]interface{}) map[string]interface{} {
if val == nil { if val == nil {
// Iterate over the values and remove nil keys // Iterate over the values and remove nil keys
delete(valsCopyMap, key) delete(valsCopyMap, key)
} else if istable(val) { } else if isTable(val) {
// Recursively call into ourselves to remove keys from inner tables // Recursively call into ourselves to remove keys from inner tables
valsCopyMap[key] = trimNilValues(val.(map[string]interface{})) valsCopyMap[key] = trimNilValues(val.(map[string]interface{}))
} }

@ -40,9 +40,9 @@ func ValidateAgainstSchema(chrt *chart.Chart, values map[string]interface{}) err
} }
// For each dependency, recursively call this function with the coalesced values // For each dependency, recursively call this function with the coalesced values
for _, subchart := range chrt.Dependencies() { for _, subChart := range chrt.Dependencies() {
subchartValues := values[subchart.Name()].(map[string]interface{}) subChartValues := values[subChart.Name()].(map[string]interface{})
if err := ValidateAgainstSchema(subchart, subchartValues); err != nil { if err := ValidateAgainstSchema(subChart, subChartValues); err != nil {
sb.WriteString(err.Error()) sb.WriteString(err.Error())
} }
} }

@ -52,14 +52,14 @@ func SaveDir(c *chart.Chart, dest string) error {
} }
// Save the chart file. // Save the chart file.
if err := SaveChartfile(filepath.Join(outdir, ChartfileName), c.Metadata); err != nil { if err := SaveChartFile(filepath.Join(outdir, ChartFileName), c.Metadata); err != nil {
return err return err
} }
// Save values.yaml // Save values.yaml
for _, f := range c.Raw { for _, f := range c.Raw {
if f.Name == ValuesfileName { if f.Name == ValuesFileName {
vf := filepath.Join(outdir, ValuesfileName) vf := filepath.Join(outdir, ValuesFileName)
if err := writeFile(vf, f.Data); err != nil { if err := writeFile(vf, f.Data); err != nil {
return err return err
} }
@ -68,7 +68,7 @@ func SaveDir(c *chart.Chart, dest string) error {
// Save values.schema.json if it exists // Save values.schema.json if it exists
if c.Schema != nil { if c.Schema != nil {
filename := filepath.Join(outdir, SchemafileName) filename := filepath.Join(outdir, SchemaFileName)
if err := writeFile(filename, c.Schema); err != nil { if err := writeFile(filename, c.Schema); err != nil {
return err return err
} }
@ -173,7 +173,7 @@ func writeTarContents(out *tar.Writer, c *chart.Chart, prefix string) error {
if err != nil { if err != nil {
return err return err
} }
if err := writeToTar(out, filepath.Join(base, ChartfileName), cdata); err != nil { if err := writeToTar(out, filepath.Join(base, ChartFileName), cdata); err != nil {
return err return err
} }
@ -193,8 +193,8 @@ func writeTarContents(out *tar.Writer, c *chart.Chart, prefix string) error {
// Save values.yaml // Save values.yaml
for _, f := range c.Raw { for _, f := range c.Raw {
if f.Name == ValuesfileName { if f.Name == ValuesFileName {
if err := writeToTar(out, filepath.Join(base, ValuesfileName), f.Data); err != nil { if err := writeToTar(out, filepath.Join(base, ValuesFileName), f.Data); err != nil {
return err return err
} }
} }
@ -203,9 +203,9 @@ func writeTarContents(out *tar.Writer, c *chart.Chart, prefix string) error {
// Save values.schema.json if it exists // Save values.schema.json if it exists
if c.Schema != nil { if c.Schema != nil {
if !json.Valid(c.Schema) { if !json.Valid(c.Schema) {
return errors.New("Invalid JSON in " + SchemafileName) return errors.New("Invalid JSON in " + SchemaFileName)
} }
if err := writeToTar(out, filepath.Join(base, SchemafileName), c.Schema); err != nil { if err := writeToTar(out, filepath.Join(base, SchemaFileName), c.Schema); err != nil {
return err return err
} }
} }

@ -165,14 +165,14 @@ func ToRenderValues(chrt *chart.Chart, chrtVals map[string]interface{}, options
return top, nil return top, nil
} }
// istable is a special-purpose function to see if the present thing matches the definition of a YAML table. // isTable is a special-purpose function to see if the present thing matches the definition of a YAML table.
func istable(v interface{}) bool { func isTable(v interface{}) bool {
_, ok := v.(map[string]interface{}) _, ok := v.(map[string]interface{})
return ok return ok
} }
// PathValue takes a path that traverses a YAML structure and returns the value at the end of that path. // PathValue takes a path that traverses a YAML structure and returns the value at the end of that path.
// The path starts at the root of the YAML structure and is comprised of YAML keys separated by periods. // The path starts at the root of the YAML structure and comprises YAML keys separated by periods.
// Given the following YAML data the value at path "chapter.one.title" is "Loomings". // Given the following YAML data the value at path "chapter.one.title" is "Loomings".
// //
// chapter: // chapter:
@ -188,7 +188,7 @@ func (v Values) PathValue(path string) (interface{}, error) {
func (v Values) pathValue(path []string) (interface{}, error) { func (v Values) pathValue(path []string) (interface{}, error) {
if len(path) == 1 { if len(path) == 1 {
// if exists must be root key not table // if exists must be root key not table
if _, ok := v[path[0]]; ok && !istable(v[path[0]]) { if _, ok := v[path[0]]; ok && !isTable(v[path[0]]) {
return v[path[0]], nil return v[path[0]], nil
} }
return nil, ErrNoValue{path[0]} return nil, ErrNoValue{path[0]}
@ -201,7 +201,7 @@ func (v Values) pathValue(path []string) (interface{}, error) {
return nil, ErrNoValue{key} return nil, ErrNoValue{key}
} }
// check table for key and ensure value is not a table // check table for key and ensure value is not a table
if k, ok := t[key]; ok && !istable(k) { if k, ok := t[key]; ok && !isTable(k) {
return k, nil return k, nil
} }
return nil, ErrNoValue{key} return nil, ErrNoValue{key}

@ -17,7 +17,7 @@ limitations under the License.
/* /*
Package cli describes the operating environment for the Helm CLI. Package cli describes the operating environment for the Helm CLI.
Helm's environment encapsulates all of the service dependencies Helm has. Helm's environment encapsulates all the service dependencies Helm has.
These dependencies are expressed as interfaces so that alternate implementations These dependencies are expressed as interfaces so that alternate implementations
(mocks, etc.) can be easily generated. (mocks, etc.) can be easily generated.
*/ */
@ -47,7 +47,7 @@ const defaultBurstLimit = 100
// defaultQPS sets the default QPS value to 0 to use library defaults unless specified // defaultQPS sets the default QPS value to 0 to use library defaults unless specified
const defaultQPS = float32(0) const defaultQPS = float32(0)
// EnvSettings describes all of the environment settings. // EnvSettings describes all the environment settings.
type EnvSettings struct { type EnvSettings struct {
namespace string namespace string
config *genericclioptions.ConfigFlags config *genericclioptions.ConfigFlags
@ -72,7 +72,7 @@ type EnvSettings struct {
// KubeTLSServerName overrides the name to use for server certificate validation. // KubeTLSServerName overrides the name to use for server certificate validation.
// If it is not provided, the hostname used to contact the server is used // If it is not provided, the hostname used to contact the server is used
KubeTLSServerName string KubeTLSServerName string
// Debug indicates whether or not Helm is running in Debug mode. // Debug indicates whether Helm is running in Debug mode.
Debug bool Debug bool
// RegistryConfig is the path to the registry config file. // RegistryConfig is the path to the registry config file.
RegistryConfig string RegistryConfig string
@ -80,7 +80,7 @@ type EnvSettings struct {
RepositoryConfig string RepositoryConfig string
// RepositoryCache is the path to the repository cache directory. // RepositoryCache is the path to the repository cache directory.
RepositoryCache string RepositoryCache string
// PluginsDirectory is the path to the plugins directory. // PluginsDirectory is the path to the plugins' directory.
PluginsDirectory string PluginsDirectory string
// MaxHistory is the max release history maintained. // MaxHistory is the max release history maintained.
MaxHistory int MaxHistory int

@ -108,9 +108,9 @@ func (c *ChartDownloader) DownloadTo(ref, version, dest string) (string, *proven
name = fmt.Sprintf("%s-%s.tgz", name[:idx], name[idx+1:]) name = fmt.Sprintf("%s-%s.tgz", name[:idx], name[idx+1:])
} }
destfile := filepath.Join(dest, name) destFile := filepath.Join(dest, name)
if err := fileutil.AtomicWriteFile(destfile, data, 0644); err != nil { if err := fileutil.AtomicWriteFile(destFile, data, 0644); err != nil {
return destfile, nil, err return destFile, nil, err
} }
// If provenance is requested, verify it. // If provenance is requested, verify it.
@ -119,26 +119,26 @@ func (c *ChartDownloader) DownloadTo(ref, version, dest string) (string, *proven
body, err := g.Get(u.String() + ".prov") body, err := g.Get(u.String() + ".prov")
if err != nil { if err != nil {
if c.Verify == VerifyAlways { if c.Verify == VerifyAlways {
return destfile, ver, errors.Errorf("failed to fetch provenance %q", u.String()+".prov") return destFile, ver, errors.Errorf("failed to fetch provenance %q", u.String()+".prov")
} }
fmt.Fprintf(c.Out, "WARNING: Verification not found for %s: %s\n", ref, err) _, _ = fmt.Fprintf(c.Out, "WARNING: Verification not found for %s: %s\n", ref, err)
return destfile, ver, nil return destFile, ver, nil
} }
provfile := destfile + ".prov" provFile := destFile + ".prov"
if err := fileutil.AtomicWriteFile(provfile, body, 0644); err != nil { if err := fileutil.AtomicWriteFile(provFile, body, 0644); err != nil {
return destfile, nil, err return destFile, nil, err
} }
if c.Verify != VerifyLater { if c.Verify != VerifyLater {
ver, err = VerifyChart(destfile, c.Keyring) ver, err = VerifyChart(destFile, c.Keyring)
if err != nil { if err != nil {
// Fail always in this case, since it means the verification step // Fail always in this case, since it means the verification step
// failed. // failed.
return destfile, ver, err return destFile, ver, err
} }
} }
} }
return destfile, ver, nil return destFile, ver, nil
} }
func (c *ChartDownloader) getOciURI(ref, version string, u *url.URL) (*url.URL, error) { func (c *ChartDownloader) getOciURI(ref, version string, u *url.URL) (*url.URL, error) {

@ -267,13 +267,13 @@ func (m *Manager) downloadAll(deps []*chart.Dependency) error {
} }
defer os.RemoveAll(tmpPath) defer os.RemoveAll(tmpPath)
fmt.Fprintf(m.Out, "Saving %d charts\n", len(deps)) _, _ = fmt.Fprintf(m.Out, "Saving %d charts\n", len(deps))
var saveError error var saveError error
churls := make(map[string]struct{}) churls := make(map[string]struct{})
for _, dep := range deps { for _, dep := range deps {
// No repository means the chart is in charts directory // No repository means the chart is in charts directory
if dep.Repository == "" { if dep.Repository == "" {
fmt.Fprintf(m.Out, "Dependency %s did not declare a repository. Assuming it exists in the charts directory\n", dep.Name) _, _ = fmt.Fprintf(m.Out, "Dependency %s did not declare a repository. Assuming it exists in the charts directory\n", dep.Name)
// NOTE: we are only validating the local dependency conforms to the constraints. No copying to tmpPath is necessary. // NOTE: we are only validating the local dependency conforms to the constraints. No copying to tmpPath is necessary.
chartPath := filepath.Join(destPath, dep.Name) chartPath := filepath.Join(destPath, dep.Name)
ch, err := loader.LoadDir(chartPath) ch, err := loader.LoadDir(chartPath)
@ -299,7 +299,7 @@ func (m *Manager) downloadAll(deps []*chart.Dependency) error {
} }
if strings.HasPrefix(dep.Repository, "file://") { if strings.HasPrefix(dep.Repository, "file://") {
if m.Debug { if m.Debug {
fmt.Fprintf(m.Out, "Archiving %s from repo %s\n", dep.Name, dep.Repository) _, _ = fmt.Fprintf(m.Out, "Archiving %s from repo %s\n", dep.Name, dep.Repository)
} }
ver, err := tarFromLocalDir(m.ChartPath, dep.Name, dep.Repository, dep.Version, tmpPath) ver, err := tarFromLocalDir(m.ChartPath, dep.Name, dep.Repository, dep.Version, tmpPath)
if err != nil { if err != nil {
@ -319,11 +319,11 @@ func (m *Manager) downloadAll(deps []*chart.Dependency) error {
} }
if _, ok := churls[churl]; ok { if _, ok := churls[churl]; ok {
fmt.Fprintf(m.Out, "Already downloaded %s from repo %s\n", dep.Name, dep.Repository) _, _ = fmt.Fprintf(m.Out, "Already downloaded %s from repo %s\n", dep.Name, dep.Repository)
continue continue
} }
fmt.Fprintf(m.Out, "Downloading %s from repo %s\n", dep.Name, dep.Repository) _, _ = fmt.Fprintf(m.Out, "Downloading %s from repo %s\n", dep.Name, dep.Repository)
dl := ChartDownloader{ dl := ChartDownloader{
Out: m.Out, Out: m.Out,
@ -367,7 +367,7 @@ func (m *Manager) downloadAll(deps []*chart.Dependency) error {
return err return err
} }
} else { } else {
fmt.Fprintln(m.Out, "Save error occurred: ", saveError) _, _ = fmt.Fprintln(m.Out, "Save error occurred: ", saveError)
return saveError return saveError
} }
return nil return nil
@ -424,24 +424,24 @@ func (m *Manager) safeMoveDeps(deps []*chart.Dependency, source, dest string) er
destfile := filepath.Join(dest, filename) destfile := filepath.Join(dest, filename)
existsInSourceDirectory[filename] = true existsInSourceDirectory[filename] = true
if _, err := loader.LoadFile(sourcefile); err != nil { if _, err := loader.LoadFile(sourcefile); err != nil {
fmt.Fprintf(m.Out, "Could not verify %s for moving: %s (Skipping)", sourcefile, err) _, _ = fmt.Fprintf(m.Out, "Could not verify %s for moving: %s (Skipping)", sourcefile, err)
continue continue
} }
// NOTE: no need to delete the dest; os.Rename replaces it. // NOTE: no need to delete the dest; os.Rename replaces it.
if err := fs.RenameWithFallback(sourcefile, destfile); err != nil { if err := fs.RenameWithFallback(sourcefile, destfile); err != nil {
fmt.Fprintf(m.Out, "Unable to move %s to charts dir %s (Skipping)", sourcefile, err) _, _ = fmt.Fprintf(m.Out, "Unable to move %s to charts dir %s (Skipping)", sourcefile, err)
continue continue
} }
} }
fmt.Fprintln(m.Out, "Deleting outdated charts") _, _ = fmt.Fprintln(m.Out, "Deleting outdated charts")
// find all files that exist in dest that do not exist in source; delete them (outdated dependencies) // find all files that exist in dest that do not exist in source; delete them (outdated dependencies)
for _, file := range destFiles { for _, file := range destFiles {
if !file.IsDir() && !existsInSourceDirectory[file.Name()] { if !file.IsDir() && !existsInSourceDirectory[file.Name()] {
fname := filepath.Join(dest, file.Name()) fname := filepath.Join(dest, file.Name())
ch, err := loader.LoadFile(fname) ch, err := loader.LoadFile(fname)
if err != nil { if err != nil {
fmt.Fprintf(m.Out, "Could not verify %s for deletion: %s (Skipping)\n", fname, err) _, _ = fmt.Fprintf(m.Out, "Could not verify %s for deletion: %s (Skipping)\n", fname, err)
continue continue
} }
// local dependency - skip // local dependency - skip
@ -449,7 +449,7 @@ func (m *Manager) safeMoveDeps(deps []*chart.Dependency, source, dest string) er
continue continue
} }
if err := os.Remove(fname); err != nil { if err := os.Remove(fname); err != nil {
fmt.Fprintf(m.Out, "Could not delete %s: %s (Skipping)", fname, err) _, _ = fmt.Fprintf(m.Out, "Could not delete %s: %s (Skipping)", fname, err)
continue continue
} }
} }
@ -545,7 +545,7 @@ func (m *Manager) ensureMissingRepos(repoNames map[string]string, deps []*chart.
// the dependencies that are not known to the user if update skipping // the dependencies that are not known to the user if update skipping
// is not configured. // is not configured.
if !m.SkipUpdate && len(ru) > 0 { if !m.SkipUpdate && len(ru) > 0 {
fmt.Fprintln(m.Out, "Getting updates for unmanaged Helm repositories...") _, _ = fmt.Fprintln(m.Out, "Getting updates for unmanaged Helm repositories...")
if err := m.parallelRepoUpdate(ru); err != nil { if err := m.parallelRepoUpdate(ru); err != nil {
return repoNames, err return repoNames, err
} }
@ -583,7 +583,7 @@ func (m *Manager) resolveRepoNames(deps []*chart.Dependency) (map[string]string,
} }
if m.Debug { if m.Debug {
fmt.Fprintf(m.Out, "Repository from local path: %s\n", dd.Repository) _, _ = fmt.Fprintf(m.Out, "Repository from local path: %s\n", dd.Repository)
} }
reposMap[dd.Name] = dd.Repository reposMap[dd.Name] = dd.Repository
continue continue
@ -649,12 +649,12 @@ func (m *Manager) UpdateRepositories() error {
} }
repos := rf.Repositories repos := rf.Repositories
if len(repos) > 0 { if len(repos) > 0 {
fmt.Fprintln(m.Out, "Hang tight while we grab the latest from your chart repositories...") _, _ = fmt.Fprintln(m.Out, "Hang tight while we grab the latest from your chart repositories...")
// This prints warnings straight to out. // This prints warnings straight to out.
if err := m.parallelRepoUpdate(repos); err != nil { if err := m.parallelRepoUpdate(repos); err != nil {
return err return err
} }
fmt.Fprintln(m.Out, "Update Complete. ⎈Happy Helming!⎈") _, _ = fmt.Fprintln(m.Out, "Update Complete. ⎈Happy Helming!⎈")
} }
return nil return nil
} }
@ -674,17 +674,17 @@ func (m *Manager) parallelRepoUpdate(repos []*repo.Entry) error {
// For those dependencies that are not known to helm and using a // For those dependencies that are not known to helm and using a
// generated key name we display the repo url. // generated key name we display the repo url.
if strings.HasPrefix(r.Config.Name, managerKeyPrefix) { if strings.HasPrefix(r.Config.Name, managerKeyPrefix) {
fmt.Fprintf(m.Out, "...Unable to get an update from the %q chart repository:\n\t%s\n", r.Config.URL, err) _, _ = fmt.Fprintf(m.Out, "...Unable to get an update from the %q chart repository:\n\t%s\n", r.Config.URL, err)
} else { } else {
fmt.Fprintf(m.Out, "...Unable to get an update from the %q chart repository (%s):\n\t%s\n", r.Config.Name, r.Config.URL, err) _, _ = fmt.Fprintf(m.Out, "...Unable to get an update from the %q chart repository (%s):\n\t%s\n", r.Config.Name, r.Config.URL, err)
} }
} else { } else {
// For those dependencies that are not known to helm and using a // For those dependencies that are not known to helm and using a
// generated key name we display the repo url. // generated key name we display the repo url.
if strings.HasPrefix(r.Config.Name, managerKeyPrefix) { if strings.HasPrefix(r.Config.Name, managerKeyPrefix) {
fmt.Fprintf(m.Out, "...Successfully got an update from the %q chart repository\n", r.Config.URL) _, _ = fmt.Fprintf(m.Out, "...Successfully got an update from the %q chart repository\n", r.Config.URL)
} else { } else {
fmt.Fprintf(m.Out, "...Successfully got an update from the %q chart repository\n", r.Config.Name) _, _ = fmt.Fprintf(m.Out, "...Successfully got an update from the %q chart repository\n", r.Config.Name)
} }
} }
wg.Done() wg.Done()

@ -201,7 +201,7 @@ var ociProvider = Provider{
New: NewOCIGetter, New: NewOCIGetter,
} }
// All finds all of the registered getters as a list of Provider instances. // All finds all the registered getters as a list of Provider instances.
// Currently, the built-in getters and the discovered plugins with downloader // Currently, the built-in getters and the discovered plugins with downloader
// notations are collected. // notations are collected.
func All(settings *cli.EnvSettings) Providers { func All(settings *cli.EnvSettings) Providers {

@ -160,7 +160,7 @@ func TestDownload(t *testing.T) {
if r.UserAgent() != defaultUserAgent { if r.UserAgent() != defaultUserAgent {
t.Errorf("Expected '%s', got '%s'", defaultUserAgent, r.UserAgent()) t.Errorf("Expected '%s', got '%s'", defaultUserAgent, r.UserAgent())
} }
fmt.Fprint(w, expect) _, _ = fmt.Fprint(w, expect)
})) }))
defer srv.Close() defer srv.Close()
@ -187,7 +187,7 @@ func TestDownload(t *testing.T) {
if r.UserAgent() != expectedUserAgent { if r.UserAgent() != expectedUserAgent {
t.Errorf("Expected '%s', got '%s'", expectedUserAgent, r.UserAgent()) t.Errorf("Expected '%s', got '%s'", expectedUserAgent, r.UserAgent())
} }
fmt.Fprint(w, expect) _, _ = fmt.Fprint(w, expect)
})) }))
defer basicAuthSrv.Close() defer basicAuthSrv.Close()
@ -217,7 +217,7 @@ func TestDownload(t *testing.T) {
if ok || username == "username" || password == "password" { if ok || username == "username" || password == "password" {
t.Errorf("Expected request to not include but got '%v', '%s', '%s'", ok, username, password) t.Errorf("Expected request to not include but got '%v', '%s', '%s'", ok, username, password)
} }
fmt.Fprint(w, expect) _, _ = fmt.Fprint(w, expect)
})) }))
defer crossAuthSrv.Close() defer crossAuthSrv.Close()
@ -252,7 +252,7 @@ func TestDownload(t *testing.T) {
if !ok || username != "username" || password != "password" { if !ok || username != "username" || password != "password" {
t.Errorf("Expected request to use basic auth and for username == 'username' and password == 'password', got '%v', '%s', '%s'", ok, username, password) t.Errorf("Expected request to use basic auth and for username == 'username' and password == 'password', got '%v', '%s', '%s'", ok, username, password)
} }
fmt.Fprint(w, expect) _, _ = fmt.Fprint(w, expect)
})) }))
defer crossAuthSrv.Close() defer crossAuthSrv.Close()

@ -37,15 +37,15 @@ func collectPlugins(settings *cli.EnvSettings) (Providers, error) {
return nil, err return nil, err
} }
var result Providers var result Providers
for _, plugin := range plugins { for _, plg := range plugins {
for _, downloader := range plugin.Metadata.Downloaders { for _, downloader := range plg.Metadata.Downloaders {
result = append(result, Provider{ result = append(result, Provider{
Schemes: downloader.Protocols, Schemes: downloader.Protocols,
New: NewPluginGetter( New: NewPluginGetter(
downloader.Command, downloader.Command,
settings, settings,
plugin.Metadata.Name, plg.Metadata.Name,
plugin.Dir, plg.Dir,
), ),
}) })
} }

@ -34,12 +34,12 @@ const (
DataHomeEnvVar = "HELM_DATA_HOME" DataHomeEnvVar = "HELM_DATA_HOME"
) )
// lazypath is an lazy-loaded path buffer for the XDG base directory specification. // lazypath is a lazy-loaded path buffer for the XDG base directory specification.
type lazypath string type lazypath string
func (l lazypath) path(helmEnvVar, xdgEnvVar string, defaultFn func() string, elem ...string) string { func (l lazypath) path(helmEnvVar, xdgEnvVar string, defaultFn func() string, elem ...string) string {
// There is an order to checking for a path. // There is an order to check for a path.
// 1. See if a Helm specific environment variable has been set. // 1. See if a Helm specific environment variable has been set.
// 2. Check if an XDG environment variable is set // 2. Check if an XDG environment variable is set
// 3. Fall back to a default // 3. Fall back to a default

@ -175,7 +175,7 @@ func (c *Client) Get(resources ResourceList, related bool) (map[string][]runtime
vk := gvk.Version + "/" + gvk.Kind vk := gvk.Version + "/" + gvk.Kind
obj, err := getResource(info) obj, err := getResource(info)
if err != nil { if err != nil {
fmt.Fprintf(buf, "Get resource %s failed, err:%v\n", info.Name, err) _, _ = fmt.Fprintf(buf, "Get resource %s failed, err:%v\n", info.Name, err)
} else { } else {
objs[vk] = append(objs[vk], obj) objs[vk] = append(objs[vk], obj)

@ -46,6 +46,6 @@ type Factory interface {
// and which implements the common patterns for CLI interactions with generic resources. // and which implements the common patterns for CLI interactions with generic resources.
NewBuilder() *resource.Builder NewBuilder() *resource.Builder
// Returns a schema that can validate objects stored on disk. // Validator Returns a schema that can validate objects stored on disk.
Validator(validationDirective string) (validation.Schema, error) Validator(validationDirective string) (validation.Schema, error)
} }

@ -35,7 +35,7 @@ func AllWithKubeVersion(basedir string, values map[string]interface{}, namespace
chartDir, _ := filepath.Abs(basedir) chartDir, _ := filepath.Abs(basedir)
linter := support.Linter{ChartDir: chartDir} linter := support.Linter{ChartDir: chartDir}
rules.Chartfile(&linter) rules.ChartFile(&linter)
rules.ValuesWithOverrides(&linter, values) rules.ValuesWithOverrides(&linter, values)
rules.TemplatesWithKubeVersion(&linter, values, namespace, kubeVersion) rules.TemplatesWithKubeVersion(&linter, values, namespace, kubeVersion)
rules.Dependencies(&linter) rules.Dependencies(&linter)

@ -31,14 +31,14 @@ import (
"helm.sh/helm/v3/pkg/lint/support" "helm.sh/helm/v3/pkg/lint/support"
) )
// Chartfile runs a set of linter rules related to Chart.yaml file // ChartFile runs a set of linter rules related to Chart.yaml file
func Chartfile(linter *support.Linter) { func ChartFile(linter *support.Linter) {
chartFileName := "Chart.yaml" chartFileName := "Chart.yaml"
chartPath := filepath.Join(linter.ChartDir, chartFileName) chartPath := filepath.Join(linter.ChartDir, chartFileName)
linter.RunLinterRule(support.ErrorSev, chartFileName, validateChartYamlNotDirectory(chartPath)) linter.RunLinterRule(support.ErrorSev, chartFileName, validateChartYamlNotDirectory(chartPath))
chartFile, err := chartutil.LoadChartfile(chartPath) chartFile, err := chartutil.LoadChartFile(chartPath)
validChartFile := linter.RunLinterRule(support.ErrorSev, chartFileName, validateChartYamlFormat(err)) validChartFile := linter.RunLinterRule(support.ErrorSev, chartFileName, validateChartYamlFormat(err))
// Guard clause. Following linter rules require a parsable ChartFile // Guard clause. Following linter rules require a parsable ChartFile

@ -41,8 +41,8 @@ var (
nonExistingChartFilePath = filepath.Join(os.TempDir(), "Chart.yaml") nonExistingChartFilePath = filepath.Join(os.TempDir(), "Chart.yaml")
) )
var badChart, _ = chartutil.LoadChartfile(badChartFilePath) var badChart, _ = chartutil.LoadChartFile(badChartFilePath)
var badChartName, _ = chartutil.LoadChartfile(badChartNamePath) var badChartName, _ = chartutil.LoadChartFile(badChartNamePath)
// Validation functions Test // Validation functions Test
func TestValidateChartYamlNotDirectory(t *testing.T) { func TestValidateChartYamlNotDirectory(t *testing.T) {
@ -192,10 +192,10 @@ func TestValidateChartIconURL(t *testing.T) {
} }
} }
func TestChartfile(t *testing.T) { func TestChartFile(t *testing.T) {
t.Run("Chart.yaml basic validity issues", func(t *testing.T) { t.Run("Chart.yaml basic validity issues", func(t *testing.T) {
linter := support.Linter{ChartDir: badChartDir} linter := support.Linter{ChartDir: badChartDir}
Chartfile(&linter) ChartFile(&linter)
msgs := linter.Messages msgs := linter.Messages
expectedNumberOfErrorMessages := 6 expectedNumberOfErrorMessages := 6
@ -231,7 +231,7 @@ func TestChartfile(t *testing.T) {
t.Run("Chart.yaml validity issues due to type mismatch", func(t *testing.T) { t.Run("Chart.yaml validity issues due to type mismatch", func(t *testing.T) {
linter := support.Linter{ChartDir: anotherBadChartDir} linter := support.Linter{ChartDir: anotherBadChartDir}
Chartfile(&linter) ChartFile(&linter)
msgs := linter.Messages msgs := linter.Messages
expectedNumberOfErrorMessages := 3 expectedNumberOfErrorMessages := 3

@ -70,11 +70,11 @@ func mockArchiveServer() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.HasSuffix(r.URL.Path, ".tar.gz") { if !strings.HasSuffix(r.URL.Path, ".tar.gz") {
w.Header().Add("Content-Type", "text/html") w.Header().Add("Content-Type", "text/html")
fmt.Fprintln(w, "broken") _, _ = fmt.Fprintln(w, "broken")
return return
} }
w.Header().Add("Content-Type", "application/gzip") w.Header().Add("Content-Type", "application/gzip")
fmt.Fprintln(w, "test") _, _ = fmt.Fprintln(w, "test")
})) }))
} }

@ -17,6 +17,7 @@ package provenance
import ( import (
"crypto" "crypto"
"errors"
"fmt" "fmt"
"io" "io"
"os" "os"
@ -37,16 +38,16 @@ const (
// testPasswordKeyFile is a keyfile with a password. // testPasswordKeyFile is a keyfile with a password.
testPasswordKeyfile = "testdata/helm-password-key.secret" testPasswordKeyfile = "testdata/helm-password-key.secret"
// testPubfile is the public key file. // testPubFile is the public key file.
// Use `gpg --export helm-test` to export the public key. // Use `gpg --export helm-test` to export the public key.
testPubfile = "testdata/helm-test-key.pub" testPubFile = "testdata/helm-test-key.pub"
// Generated name for the PGP key in testKeyFile. // Generated name for the PGP key in testKeyFile.
testKeyName = `Helm Testing (This key should only be used for testing. DO NOT TRUST.) <helm-testing@helm.sh>` testKeyName = `Helm Testing (This key should only be used for testing. DO NOT TRUST.) <helm-testing@helm.sh>`
testPasswordKeyName = `password key (fake) <fake@helm.sh>` testPasswordKeyName = `password key (fake) <fake@helm.sh>`
testChartfile = "testdata/hashtest-1.2.3.tgz" testChartFile = "testdata/hashtest-1.2.3.tgz"
// testSigBlock points to a signature generated by an external tool. // testSigBlock points to a signature generated by an external tool.
// This file was generated with GnuPG: // This file was generated with GnuPG:
@ -56,12 +57,12 @@ const (
// testTamperedSigBlock is a tampered copy of msgblock.yaml.asc // testTamperedSigBlock is a tampered copy of msgblock.yaml.asc
testTamperedSigBlock = "testdata/msgblock.yaml.tampered" testTamperedSigBlock = "testdata/msgblock.yaml.tampered"
// testSumfile points to a SHA256 sum generated by an external tool. // testSumFile points to a SHA256 sum generated by an external tool.
// We always want to validate against an external tool's representation to // We always want to validate against an external tool's representation to
// verify that we haven't done something stupid. This file was generated // verify that we haven't done something stupid. This file was generated
// with shasum. // with shasum.
// shasum -a 256 hashtest-1.2.3.tgz > testdata/hashtest.sha256 // shasum -a 256 hashtest-1.2.3.tgz > testdata/hashtest.sha256
testSumfile = "testdata/hashtest.sha256" testSumFile = "testdata/hashtest.sha256"
) )
// testMessageBlock represents the expected message block for the testdata/hashtest chart. // testMessageBlock represents the expected message block for the testdata/hashtest chart.
@ -76,7 +77,7 @@ files:
` `
func TestMessageBlock(t *testing.T) { func TestMessageBlock(t *testing.T) {
out, err := messageBlock(testChartfile) out, err := messageBlock(testChartFile)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -120,7 +121,7 @@ func TestLoadKey(t *testing.T) {
} }
func TestLoadKeyRing(t *testing.T) { func TestLoadKeyRing(t *testing.T) {
k, err := loadKeyRing(testPubfile) k, err := loadKeyRing(testPubFile)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -137,7 +138,7 @@ func TestLoadKeyRing(t *testing.T) {
} }
func TestDigest(t *testing.T) { func TestDigest(t *testing.T) {
f, err := os.Open(testChartfile) f, err := os.Open(testChartFile)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -148,7 +149,7 @@ func TestDigest(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
sig, err := readSumFile(testSumfile) sig, err := readSumFile(testSumFile)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -159,7 +160,7 @@ func TestDigest(t *testing.T) {
} }
func TestNewFromFiles(t *testing.T) { func TestNewFromFiles(t *testing.T) {
s, err := NewFromFiles(testKeyfile, testPubfile) s, err := NewFromFiles(testKeyfile, testPubFile)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -170,12 +171,12 @@ func TestNewFromFiles(t *testing.T) {
} }
func TestDigestFile(t *testing.T) { func TestDigestFile(t *testing.T) {
hash, err := DigestFile(testChartfile) hash, err := DigestFile(testChartFile)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
sig, err := readSumFile(testSumfile) sig, err := readSumFile(testSumFile)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -216,12 +217,12 @@ func TestDecryptKey(t *testing.T) {
} }
func TestClearSign(t *testing.T) { func TestClearSign(t *testing.T) {
signer, err := NewFromFiles(testKeyfile, testPubfile) signer, err := NewFromFiles(testKeyfile, testPubFile)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
sig, err := signer.ClearSign(testChartfile) sig, err := signer.ClearSign(testChartFile)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -244,7 +245,7 @@ func (s failSigner) Sign(_ io.Reader, _ []byte, _ crypto.SignerOpts) ([]byte, er
} }
func TestClearSignError(t *testing.T) { func TestClearSignError(t *testing.T) {
signer, err := NewFromFiles(testKeyfile, testPubfile) signer, err := NewFromFiles(testKeyfile, testPubFile)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -252,7 +253,7 @@ func TestClearSignError(t *testing.T) {
// ensure that signing always fails // ensure that signing always fails
signer.Entity.PrivateKey.PrivateKey = failSigner{} signer.Entity.PrivateKey.PrivateKey = failSigner{}
sig, err := signer.ClearSign(testChartfile) sig, err := signer.ClearSign(testChartFile)
if err == nil { if err == nil {
t.Fatal("didn't get an error from ClearSign but expected one") t.Fatal("didn't get an error from ClearSign but expected one")
} }
@ -266,12 +267,12 @@ func TestDecodeSignature(t *testing.T) {
// Unlike other tests, this does a round-trip test, ensuring that a signature // Unlike other tests, this does a round-trip test, ensuring that a signature
// generated by the library can also be verified by the library. // generated by the library can also be verified by the library.
signer, err := NewFromFiles(testKeyfile, testPubfile) signer, err := NewFromFiles(testKeyfile, testPubFile)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
sig, err := signer.ClearSign(testChartfile) sig, err := signer.ClearSign(testChartFile)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -281,14 +282,14 @@ func TestDecodeSignature(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
tname := f.Name() tName := f.Name()
defer func() { defer func() {
os.Remove(tname) _ = os.Remove(tName)
}() }()
f.WriteString(sig) _, _ = f.WriteString(sig)
f.Close() _ = f.Close()
sig2, err := signer.decodeSignature(tname) sig2, err := signer.decodeSignature(tName)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -304,27 +305,28 @@ func TestDecodeSignature(t *testing.T) {
} }
func TestVerify(t *testing.T) { func TestVerify(t *testing.T) {
signer, err := NewFromFiles(testKeyfile, testPubfile) signer, err := NewFromFiles(testKeyfile, testPubFile)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if ver, err := signer.Verify(testChartfile, testSigBlock); err != nil { if ver, err := signer.Verify(testChartFile, testSigBlock); err != nil {
t.Errorf("Failed to pass verify. Err: %s", err) t.Errorf("Failed to pass verify. Err: %s", err)
} else if len(ver.FileHash) == 0 { } else if len(ver.FileHash) == 0 {
t.Error("Verification is missing hash.") t.Error("Verification is missing hash.")
} else if ver.SignedBy == nil { } else if ver.SignedBy == nil {
t.Error("No SignedBy field") t.Error("No SignedBy field")
} else if ver.FileName != filepath.Base(testChartfile) { } else if ver.FileName != filepath.Base(testChartFile) {
t.Errorf("FileName is unexpectedly %q", ver.FileName) t.Errorf("FileName is unexpectedly %q", ver.FileName)
} }
if _, err = signer.Verify(testChartfile, testTamperedSigBlock); err == nil { if _, err = signer.Verify(testChartFile, testTamperedSigBlock); err == nil {
t.Errorf("Expected %s to fail.", testTamperedSigBlock) t.Errorf("Expected %s to fail.", testTamperedSigBlock)
} }
switch err.(type) { var signatureError pgperrors.SignatureError
case pgperrors.SignatureError: switch {
case errors.As(err, &signatureError):
t.Logf("Tampered sig block error: %s (%T)", err, err) t.Logf("Tampered sig block error: %s (%T)", err, err)
default: default:
t.Errorf("Expected invalid signature error, got %q (%T)", err, err) t.Errorf("Expected invalid signature error, got %q (%T)", err, err)
@ -332,8 +334,8 @@ func TestVerify(t *testing.T) {
} }
// readSumFile reads a file containing a sum generated by the UNIX shasum tool. // readSumFile reads a file containing a sum generated by the UNIX shasum tool.
func readSumFile(sumfile string) (string, error) { func readSumFile(sumFile string) (string, error) {
data, err := os.ReadFile(sumfile) data, err := os.ReadFile(sumFile)
if err != nil { if err != nil {
return "", err return "", err
} }

@ -238,7 +238,7 @@ func (c *Client) Login(host string, options ...LoginOption) error {
if err := c.authorizer.LoginWithOpts(authorizerLoginOpts...); err != nil { if err := c.authorizer.LoginWithOpts(authorizerLoginOpts...); err != nil {
return err return err
} }
fmt.Fprintln(c.out, "Login Succeeded") _, _ = fmt.Fprintln(c.out, "Login Succeeded")
return nil return nil
} }
@ -282,7 +282,7 @@ func (c *Client) Logout(host string, opts ...LogoutOption) error {
if err := c.authorizer.Logout(ctx(c.out, c.debug), host); err != nil { if err := c.authorizer.Logout(ctx(c.out, c.debug), host); err != nil {
return err return err
} }
fmt.Fprintf(c.out, "Removing login credentials for %s\n", host) _, _ = fmt.Fprintf(c.out, "Removing login credentials for %s\n", host)
return nil return nil
} }
@ -389,7 +389,7 @@ func (c *Client) Pull(ref string, options ...PullOption) (*PullResult, error) {
provDescriptor = &d provDescriptor = &d
case LegacyChartLayerMediaType: case LegacyChartLayerMediaType:
chartDescriptor = &d chartDescriptor = &d
fmt.Fprintf(c.out, "Warning: chart media type %s is deprecated\n", LegacyChartLayerMediaType) _, _ = fmt.Fprintf(c.out, "Warning: chart media type %s is deprecated\n", LegacyChartLayerMediaType)
} }
} }
if configDescriptor == nil { if configDescriptor == nil {
@ -471,12 +471,12 @@ func (c *Client) Pull(ref string, options ...PullOption) (*PullResult, error) {
} }
} }
fmt.Fprintf(c.out, "Pulled: %s\n", result.Ref) _, _ = fmt.Fprintf(c.out, "Pulled: %s\n", result.Ref)
fmt.Fprintf(c.out, "Digest: %s\n", result.Manifest.Digest) _, _ = fmt.Fprintf(c.out, "Digest: %s\n", result.Manifest.Digest)
if strings.Contains(result.Ref, "_") { if strings.Contains(result.Ref, "_") {
fmt.Fprintf(c.out, "%s contains an underscore.\n", result.Ref) _, _ = fmt.Fprintf(c.out, "%s contains an underscore.\n", result.Ref)
fmt.Fprint(c.out, registryUnderscoreMessage+"\n") _, _ = fmt.Fprint(c.out, registryUnderscoreMessage+"\n")
} }
return result, nil return result, nil
@ -628,11 +628,11 @@ func (c *Client) Push(data []byte, ref string, options ...PushOption) (*PushResu
Size: provDescriptor.Size, Size: provDescriptor.Size,
} }
} }
fmt.Fprintf(c.out, "Pushed: %s\n", result.Ref) _, _ = fmt.Fprintf(c.out, "Pushed: %s\n", result.Ref)
fmt.Fprintf(c.out, "Digest: %s\n", result.Manifest.Digest) _, _ = fmt.Fprintf(c.out, "Digest: %s\n", result.Manifest.Digest)
if strings.Contains(parsedRef.Reference, "_") { if strings.Contains(parsedRef.Reference, "_") {
fmt.Fprintf(c.out, "%s contains an underscore.\n", result.Ref) _, _ = fmt.Fprintf(c.out, "%s contains an underscore.\n", result.Ref)
fmt.Fprint(c.out, registryUnderscoreMessage+"\n") _, _ = fmt.Fprint(c.out, registryUnderscoreMessage+"\n")
} }
return result, err return result, err

@ -44,7 +44,7 @@ var immutableOciAnnotations = []string{
ocispec.AnnotationTitle, ocispec.AnnotationTitle,
} }
// IsOCI determines whether or not a URL is to be treated as an OCI URL // IsOCI determines whether a URL is to be treated as an OCI URL
func IsOCI(url string) bool { func IsOCI(url string) bool {
return strings.HasPrefix(url, fmt.Sprintf("%s://", OCIScheme)) return strings.HasPrefix(url, fmt.Sprintf("%s://", OCIScheme))
} }

@ -144,7 +144,7 @@ func (r *ChartRepository) DownloadIndexFile() (string, error) {
// Create the chart list file in the cache directory // Create the chart list file in the cache directory
var charts strings.Builder var charts strings.Builder
for name := range indexFile.Entries { for name := range indexFile.Entries {
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), 0755) os.MkdirAll(filepath.Dir(chartsFile), 0755)

Loading…
Cancel
Save