repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/repo_update.go
pkg/cmd/repo_update.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "errors" "fmt" "io" "slices" "sync" "time" "github.com/spf13/cobra" "helm.sh/helm/v4/pkg/cmd/require" "helm.sh/helm/v4/pkg/getter" "helm.sh/helm/v4/pkg/repo/v1" ) const updateDesc = ` Update gets the latest information about charts from the respective chart repositories. Information is cached locally, where it is used by commands like 'helm search'. You can optionally specify a list of repositories you want to update. $ helm repo update <repo_name> ... To update all the repositories, use 'helm repo update'. ` var errNoRepositories = errors.New("no repositories found. You must add one before updating") type repoUpdateOptions struct { update func([]*repo.ChartRepository, io.Writer) error repoFile string repoCache string names []string timeout time.Duration } func newRepoUpdateCmd(out io.Writer) *cobra.Command { o := &repoUpdateOptions{update: updateCharts} cmd := &cobra.Command{ Use: "update [REPO1 [REPO2 ...]]", Aliases: []string{"up"}, Short: "update information of available charts locally from chart repositories", Long: updateDesc, Args: require.MinimumNArgs(0), ValidArgsFunction: func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return compListRepos(toComplete, args), cobra.ShellCompDirectiveNoFileComp }, RunE: func(_ *cobra.Command, args []string) error { o.repoFile = settings.RepositoryConfig o.repoCache = settings.RepositoryCache o.names = args return o.run(out) }, } f := cmd.Flags() f.DurationVar(&o.timeout, "timeout", getter.DefaultHTTPTimeout*time.Second, "time to wait for the index file download to complete") return cmd } func (o *repoUpdateOptions) run(out io.Writer) error { f, err := repo.LoadFile(o.repoFile) switch { case isNotExist(err): return errNoRepositories case err != nil: return fmt.Errorf("failed loading file: %s: %w", o.repoFile, err) case len(f.Repositories) == 0: return errNoRepositories } var repos []*repo.ChartRepository updateAllRepos := len(o.names) == 0 if !updateAllRepos { // Fail early if the user specified an invalid repo to update if err := checkRequestedRepos(o.names, f.Repositories); err != nil { return err } } for _, cfg := range f.Repositories { if updateAllRepos || isRepoRequested(cfg.Name, o.names) { r, err := repo.NewChartRepository(cfg, getter.All(settings, getter.WithTimeout(o.timeout))) if err != nil { return err } if o.repoCache != "" { r.CachePath = o.repoCache } repos = append(repos, r) } } return o.update(repos, out) } func updateCharts(repos []*repo.ChartRepository, out io.Writer) error { fmt.Fprintln(out, "Hang tight while we grab the latest from your chart repositories...") var wg sync.WaitGroup failRepoURLChan := make(chan string, len(repos)) writeMutex := sync.Mutex{} for _, re := range repos { wg.Add(1) go func(re *repo.ChartRepository) { defer wg.Done() if _, err := re.DownloadIndexFile(); err != nil { writeMutex.Lock() defer writeMutex.Unlock() 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) failRepoURLChan <- re.Config.URL } else { writeMutex.Lock() defer writeMutex.Unlock() fmt.Fprintf(out, "...Successfully got an update from the %q chart repository\n", re.Config.Name) } }(re) } go func() { wg.Wait() close(failRepoURLChan) }() var repoFailList []string for url := range failRepoURLChan { repoFailList = append(repoFailList, url) } if len(repoFailList) > 0 { return fmt.Errorf("failed to update the following repositories: %s", repoFailList) } fmt.Fprintln(out, "Update Complete. ⎈Happy Helming!⎈") return nil } func checkRequestedRepos(requestedRepos []string, validRepos []*repo.Entry) error { for _, requestedRepo := range requestedRepos { found := false for _, repo := range validRepos { if requestedRepo == repo.Name { found = true break } } if !found { return fmt.Errorf("no repositories found matching '%s'. Nothing will be updated", requestedRepo) } } return nil } func isRepoRequested(repoName string, requestedRepos []string) bool { return slices.Contains(requestedRepos, repoName) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/docs_test.go
pkg/cmd/docs_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "testing" ) func TestDocsTypeFlagCompletion(t *testing.T) { tests := []cmdTestCase{{ name: "completion for docs --type", cmd: "__complete docs --type ''", golden: "output/docs-type-comp.txt", }, { name: "completion for docs --type, no filter", cmd: "__complete docs --type mar", golden: "output/docs-type-comp.txt", }} runTestCmd(t, tests) } func TestDocsFileCompletion(t *testing.T) { checkFileCompletion(t, "docs", false) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/create_test.go
pkg/cmd/create_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "os" "path/filepath" "testing" "helm.sh/helm/v4/internal/test/ensure" chart "helm.sh/helm/v4/pkg/chart/v2" "helm.sh/helm/v4/pkg/chart/v2/loader" chartutil "helm.sh/helm/v4/pkg/chart/v2/util" "helm.sh/helm/v4/pkg/helmpath" ) func TestCreateCmd(t *testing.T) { t.Chdir(t.TempDir()) ensure.HelmHome(t) cname := "testchart" // Run a create if _, _, err := executeActionCommand("create " + cname); err != nil { t.Fatalf("Failed to run create: %s", err) } // Test that the chart is there if fi, err := os.Stat(cname); err != nil { t.Fatalf("no chart directory: %s", err) } else if !fi.IsDir() { t.Fatalf("chart is not directory") } c, err := loader.LoadDir(cname) if err != nil { t.Fatal(err) } if c.Name() != cname { t.Errorf("Expected %q name, got %q", cname, c.Name()) } if c.Metadata.APIVersion != chart.APIVersionV2 { t.Errorf("Wrong API version: %q", c.Metadata.APIVersion) } } func TestCreateStarterCmd(t *testing.T) { t.Chdir(t.TempDir()) ensure.HelmHome(t) cname := "testchart" defer resetEnv()() // Create a starter. starterchart := helmpath.DataPath("starters") os.MkdirAll(starterchart, 0o755) if dest, err := chartutil.Create("starterchart", starterchart); err != nil { t.Fatalf("Could not create chart: %s", err) } else { t.Logf("Created %s", dest) } tplpath := filepath.Join(starterchart, "starterchart", "templates", "foo.tpl") if err := os.WriteFile(tplpath, []byte("test"), 0o644); err != nil { t.Fatalf("Could not write template: %s", err) } // Run a create if _, _, err := executeActionCommand(fmt.Sprintf("create --starter=starterchart %s", cname)); err != nil { t.Errorf("Failed to run create: %s", err) return } // Test that the chart is there if fi, err := os.Stat(cname); err != nil { t.Fatalf("no chart directory: %s", err) } else if !fi.IsDir() { t.Fatalf("chart is not directory") } c, err := loader.LoadDir(cname) if err != nil { t.Fatal(err) } if c.Name() != cname { t.Errorf("Expected %q name, got %q", cname, c.Name()) } if c.Metadata.APIVersion != chart.APIVersionV2 { t.Errorf("Wrong API version: %q", c.Metadata.APIVersion) } expectedNumberOfTemplates := 10 if l := len(c.Templates); l != expectedNumberOfTemplates { t.Errorf("Expected %d templates, got %d", expectedNumberOfTemplates, l) } found := false for _, tpl := range c.Templates { if tpl.Name == "templates/foo.tpl" { found = true if data := string(tpl.Data); data != "test" { t.Errorf("Expected template 'test', got %q", data) } } } if !found { t.Error("Did not find foo.tpl") } } func TestCreateStarterAbsoluteCmd(t *testing.T) { t.Chdir(t.TempDir()) defer resetEnv()() ensure.HelmHome(t) cname := "testchart" // Create a starter. starterchart := helmpath.DataPath("starters") os.MkdirAll(starterchart, 0o755) if dest, err := chartutil.Create("starterchart", starterchart); err != nil { t.Fatalf("Could not create chart: %s", err) } else { t.Logf("Created %s", dest) } tplpath := filepath.Join(starterchart, "starterchart", "templates", "foo.tpl") if err := os.WriteFile(tplpath, []byte("test"), 0o644); err != nil { t.Fatalf("Could not write template: %s", err) } starterChartPath := filepath.Join(starterchart, "starterchart") // Run a create if _, _, err := executeActionCommand(fmt.Sprintf("create --starter=%s %s", starterChartPath, cname)); err != nil { t.Errorf("Failed to run create: %s", err) return } // Test that the chart is there if fi, err := os.Stat(cname); err != nil { t.Fatalf("no chart directory: %s", err) } else if !fi.IsDir() { t.Fatalf("chart is not directory") } c, err := loader.LoadDir(cname) if err != nil { t.Fatal(err) } if c.Name() != cname { t.Errorf("Expected %q name, got %q", cname, c.Name()) } if c.Metadata.APIVersion != chart.APIVersionV2 { t.Errorf("Wrong API version: %q", c.Metadata.APIVersion) } expectedNumberOfTemplates := 10 if l := len(c.Templates); l != expectedNumberOfTemplates { t.Errorf("Expected %d templates, got %d", expectedNumberOfTemplates, l) } found := false for _, tpl := range c.Templates { if tpl.Name == "templates/foo.tpl" { found = true if data := string(tpl.Data); data != "test" { t.Errorf("Expected template 'test', got %q", data) } } } if !found { t.Error("Did not find foo.tpl") } } func TestCreateFileCompletion(t *testing.T) { checkFileCompletion(t, "create", true) checkFileCompletion(t, "create myname", false) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/rollback_test.go
pkg/cmd/rollback_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "reflect" "testing" chart "helm.sh/helm/v4/pkg/chart/v2" "helm.sh/helm/v4/pkg/release/common" release "helm.sh/helm/v4/pkg/release/v1" ) func TestRollbackCmd(t *testing.T) { rels := []*release.Release{ { Name: "funny-honey", Info: &release.Info{Status: common.StatusSuperseded}, Chart: &chart.Chart{}, Version: 1, }, { Name: "funny-honey", Info: &release.Info{Status: common.StatusDeployed}, Chart: &chart.Chart{}, Version: 2, }, } tests := []cmdTestCase{{ name: "rollback a release", cmd: "rollback funny-honey 1", golden: "output/rollback.txt", rels: rels, }, { name: "rollback a release with timeout", cmd: "rollback funny-honey 1 --timeout 120s", golden: "output/rollback-timeout.txt", rels: rels, }, { name: "rollback a release with wait", cmd: "rollback funny-honey 1 --wait", golden: "output/rollback-wait.txt", rels: rels, }, { name: "rollback a release with wait-for-jobs", cmd: "rollback funny-honey 1 --wait --wait-for-jobs", golden: "output/rollback-wait-for-jobs.txt", rels: rels, }, { name: "rollback a release without revision", cmd: "rollback funny-honey", golden: "output/rollback-no-revision.txt", rels: rels, }, { name: "rollback a release with non-existent version", cmd: "rollback funny-honey 3", golden: "output/rollback-non-existent-version.txt", rels: rels, wantError: true, }, { name: "rollback a release without release name", cmd: "rollback", golden: "output/rollback-no-args.txt", rels: rels, wantError: true, }} runTestCmd(t, tests) } func TestRollbackRevisionCompletion(t *testing.T) { mk := func(name string, vers int, status common.Status) *release.Release { return release.Mock(&release.MockReleaseOptions{ Name: name, Version: vers, Status: status, }) } releases := []*release.Release{ mk("musketeers", 11, common.StatusDeployed), mk("musketeers", 10, common.StatusSuperseded), mk("musketeers", 9, common.StatusSuperseded), mk("musketeers", 8, common.StatusSuperseded), mk("carabins", 1, common.StatusSuperseded), } tests := []cmdTestCase{{ name: "completion for release parameter", cmd: "__complete rollback ''", rels: releases, golden: "output/rollback-comp.txt", }, { name: "completion for revision parameter", cmd: "__complete rollback musketeers ''", rels: releases, golden: "output/revision-comp.txt", }, { name: "completion for with too many args", cmd: "__complete rollback musketeers 11 ''", rels: releases, golden: "output/rollback-wrong-args-comp.txt", }} runTestCmd(t, tests) } func TestRollbackFileCompletion(t *testing.T) { checkFileCompletion(t, "rollback", false) checkFileCompletion(t, "rollback myrelease", false) checkFileCompletion(t, "rollback myrelease 1", false) } func TestRollbackWithLabels(t *testing.T) { labels1 := map[string]string{"operation": "install", "firstLabel": "firstValue"} labels2 := map[string]string{"operation": "upgrade", "secondLabel": "secondValue"} releaseName := "funny-bunny-labels" rels := []*release.Release{ { Name: releaseName, Info: &release.Info{Status: common.StatusSuperseded}, Chart: &chart.Chart{}, Version: 1, Labels: labels1, }, { Name: releaseName, Info: &release.Info{Status: common.StatusDeployed}, Chart: &chart.Chart{}, Version: 2, Labels: labels2, }, } storage := storageFixture() for _, rel := range rels { if err := storage.Create(rel); err != nil { t.Fatal(err) } } _, _, err := executeActionCommandC(storage, fmt.Sprintf("rollback %s 1", releaseName)) if err != nil { t.Errorf("unexpected error, got '%v'", err) } updatedReli, err := storage.Get(releaseName, 3) if err != nil { t.Errorf("unexpected error, got '%v'", err) } updatedRel, err := releaserToV1Release(updatedReli) if err != nil { t.Errorf("unexpected error, got '%v'", err) } if !reflect.DeepEqual(updatedRel.Labels, labels1) { t.Errorf("Expected {%v}, got {%v}", labels1, updatedRel.Labels) } }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/repo_remove.go
pkg/cmd/repo_remove.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "errors" "fmt" "io" "io/fs" "os" "path/filepath" "github.com/spf13/cobra" "helm.sh/helm/v4/pkg/cmd/require" "helm.sh/helm/v4/pkg/helmpath" "helm.sh/helm/v4/pkg/repo/v1" ) type repoRemoveOptions struct { names []string repoFile string repoCache string } func newRepoRemoveCmd(out io.Writer) *cobra.Command { o := &repoRemoveOptions{} cmd := &cobra.Command{ Use: "remove [REPO1 [REPO2 ...]]", Aliases: []string{"rm"}, Short: "remove one or more chart repositories", Args: require.MinimumNArgs(1), ValidArgsFunction: func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return compListRepos(toComplete, args), cobra.ShellCompDirectiveNoFileComp }, RunE: func(_ *cobra.Command, args []string) error { o.repoFile = settings.RepositoryConfig o.repoCache = settings.RepositoryCache o.names = args return o.run(out) }, } return cmd } func (o *repoRemoveOptions) run(out io.Writer) error { r, err := repo.LoadFile(o.repoFile) if isNotExist(err) || len(r.Repositories) == 0 { return errors.New("no repositories configured") } for _, name := range o.names { if !r.Remove(name) { return fmt.Errorf("no repo named %q found", name) } if err := r.WriteFile(o.repoFile, 0600); err != nil { return err } if err := removeRepoCache(o.repoCache, name); err != nil { return err } fmt.Fprintf(out, "%q has been removed from your repositories\n", name) } return nil } func removeRepoCache(root, name string) error { idx := filepath.Join(root, helmpath.CacheChartsFile(name)) if _, err := os.Stat(idx); err == nil { os.Remove(idx) } idx = filepath.Join(root, helmpath.CacheIndexFile(name)) if _, err := os.Stat(idx); errors.Is(err, fs.ErrNotExist) { return nil } else if err != nil { return fmt.Errorf("can't remove index file %s: %w", idx, err) } return os.Remove(idx) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/search_repo_test.go
pkg/cmd/search_repo_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "testing" ) func TestSearchRepositoriesCmd(t *testing.T) { repoFile := "testdata/helmhome/helm/repositories.yaml" repoCache := "testdata/helmhome/helm/repository" tests := []cmdTestCase{{ name: "search for 'alpine', expect one match with latest stable version", cmd: "search repo alpine", golden: "output/search-multiple-stable-release.txt", }, { name: "search for 'alpine', expect one match with newest development version", cmd: "search repo alpine --devel", golden: "output/search-multiple-devel-release.txt", }, { name: "search for 'alpine' with versions, expect three matches", cmd: "search repo alpine --versions", golden: "output/search-multiple-versions.txt", }, { name: "search for 'alpine' with version constraint, expect one match with version 0.1.0", cmd: "search repo alpine --version '>= 0.1, < 0.2'", golden: "output/search-constraint.txt", }, { name: "search for 'alpine' with version constraint, expect one match with version 0.1.0", cmd: "search repo alpine --versions --version '>= 0.1, < 0.2'", golden: "output/search-versions-constraint.txt", }, { name: "search for 'alpine' with version constraint, expect one match with version 0.2.0", cmd: "search repo alpine --version '>= 0.1'", golden: "output/search-constraint-single.txt", }, { name: "search for 'alpine' with version constraint and --versions, expect two matches", cmd: "search repo alpine --versions --version '>= 0.1'", golden: "output/search-multiple-versions-constraints.txt", }, { name: "search for 'syzygy', expect no matches", cmd: "search repo syzygy", golden: "output/search-not-found.txt", }, { name: "search for 'syzygy' with --fail-on-no-result, expect failure for no results", cmd: "search repo syzygy --fail-on-no-result", golden: "output/search-not-found-error.txt", wantError: true, }, {name: "search for 'syzygy' with json output and --fail-on-no-result, expect failure for no results", cmd: "search repo syzygy --output json --fail-on-no-result", golden: "output/search-not-found-error.txt", wantError: true, }, { name: "search for 'syzygy' with yaml output --fail-on-no-result, expect failure for no results", cmd: "search repo syzygy --output yaml --fail-on-no-result", golden: "output/search-not-found-error.txt", wantError: true, }, { name: "search for 'alp[a-z]+', expect two matches", cmd: "search repo alp[a-z]+ --regexp", golden: "output/search-regex.txt", }, { name: "search for 'alp[', expect failure to compile regexp", cmd: "search repo alp[ --regexp", wantError: true, }, { name: "search for 'maria', expect valid json output", cmd: "search repo maria --output json", golden: "output/search-output-json.txt", }, { name: "search for 'alpine', expect valid yaml output", cmd: "search repo alpine --output yaml", golden: "output/search-output-yaml.txt", }} settings.Debug = true defer func() { settings.Debug = false }() for i := range tests { tests[i].cmd += " --repository-config " + repoFile tests[i].cmd += " --repository-cache " + repoCache } runTestCmd(t, tests) } func TestSearchRepoOutputCompletion(t *testing.T) { outputFlagCompletionTest(t, "search repo") } func TestSearchRepoFileCompletion(t *testing.T) { checkFileCompletion(t, "search repo", true) // File completion may be useful when inputting a keyword }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/plugin_package_test.go
pkg/cmd/plugin_package_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "bytes" "os" "path/filepath" "strings" "testing" ) // Common plugin.yaml content for v1 format tests const testPluginYAML = `apiVersion: v1 name: test-plugin version: 1.0.0 type: cli/v1 runtime: subprocess config: usage: test-plugin [flags] shortHelp: A test plugin longHelp: A test plugin for testing purposes runtimeConfig: platformCommand: - os: linux command: echo args: ["test"]` func TestPluginPackageWithoutSigning(t *testing.T) { // Create a test plugin directory tempDir := t.TempDir() pluginDir := filepath.Join(tempDir, "test-plugin") if err := os.MkdirAll(pluginDir, 0755); err != nil { t.Fatal(err) } // Create a plugin.yaml file if err := os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(testPluginYAML), 0644); err != nil { t.Fatal(err) } // Create package options with sign=false o := &pluginPackageOptions{ sign: false, // Explicitly disable signing pluginPath: pluginDir, destination: tempDir, } // Run the package command out := &bytes.Buffer{} err := o.run(out) // Should succeed without error if err != nil { t.Errorf("unexpected error: %v", err) } // Check that tarball was created with plugin name and version tarballPath := filepath.Join(tempDir, "test-plugin-1.0.0.tgz") if _, err := os.Stat(tarballPath); os.IsNotExist(err) { t.Error("tarball should exist when sign=false") } // Check that no .prov file was created provPath := tarballPath + ".prov" if _, err := os.Stat(provPath); !os.IsNotExist(err) { t.Error("provenance file should not exist when sign=false") } // Output should contain warning about skipping signing output := out.String() if !strings.Contains(output, "WARNING: Skipping plugin signing") { t.Error("should print warning when signing is skipped") } if !strings.Contains(output, "Successfully packaged") { t.Error("should print success message") } } func TestPluginPackageDefaultRequiresSigning(t *testing.T) { // Create a test plugin directory tempDir := t.TempDir() pluginDir := filepath.Join(tempDir, "test-plugin") if err := os.MkdirAll(pluginDir, 0755); err != nil { t.Fatal(err) } // Create a plugin.yaml file if err := os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(testPluginYAML), 0644); err != nil { t.Fatal(err) } // Create package options with default sign=true and invalid keyring o := &pluginPackageOptions{ sign: true, // This is now the default keyring: "/non/existent/keyring", pluginPath: pluginDir, destination: tempDir, } // Run the package command out := &bytes.Buffer{} err := o.run(out) // Should fail because signing is required by default if err == nil { t.Error("expected error when signing fails with default settings") } // Check that no tarball was created tarballPath := filepath.Join(tempDir, "test-plugin.tgz") if _, err := os.Stat(tarballPath); !os.IsNotExist(err) { t.Error("tarball should not exist when signing fails") } } func TestPluginPackageSigningFailure(t *testing.T) { // Create a test plugin directory tempDir := t.TempDir() pluginDir := filepath.Join(tempDir, "test-plugin") if err := os.MkdirAll(pluginDir, 0755); err != nil { t.Fatal(err) } // Create a plugin.yaml file if err := os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(testPluginYAML), 0644); err != nil { t.Fatal(err) } // Create package options with sign flag but invalid keyring o := &pluginPackageOptions{ sign: true, keyring: "/non/existent/keyring", // This will cause signing to fail pluginPath: pluginDir, destination: tempDir, } // Run the package command out := &bytes.Buffer{} err := o.run(out) // Should get an error if err == nil { t.Error("expected error when signing fails, got nil") } // Check that no tarball was created tarballPath := filepath.Join(tempDir, "test-plugin.tgz") if _, err := os.Stat(tarballPath); !os.IsNotExist(err) { t.Error("tarball should not exist when signing fails") } // Output should not contain success message if bytes.Contains(out.Bytes(), []byte("Successfully packaged")) { t.Error("should not print success message when signing fails") } }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/plugin_install.go
pkg/cmd/plugin_install.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "io" "log/slog" "strings" "github.com/spf13/cobra" "helm.sh/helm/v4/internal/plugin" "helm.sh/helm/v4/internal/plugin/installer" "helm.sh/helm/v4/pkg/cmd/require" "helm.sh/helm/v4/pkg/getter" "helm.sh/helm/v4/pkg/registry" ) type pluginInstallOptions struct { source string version string // signing options verify bool keyring string // OCI-specific options certFile string keyFile string caFile string insecureSkipTLSVerify bool plainHTTP bool password string username string } const pluginInstallDesc = ` This command allows you to install a plugin from a url to a VCS repo or a local path. By default, plugin signatures are verified before installation when installing from tarballs (.tgz or .tar.gz). This requires a corresponding .prov file to be available alongside the tarball. For local development, plugins installed from local directories are automatically treated as "local dev" and do not require signatures. Use --verify=false to skip signature verification for remote plugins. ` func newPluginInstallCmd(out io.Writer) *cobra.Command { o := &pluginInstallOptions{} cmd := &cobra.Command{ Use: "install [options] <path|url>", Short: "install a Helm plugin", Long: pluginInstallDesc, Aliases: []string{"add"}, Args: require.ExactArgs(1), ValidArgsFunction: func(_ *cobra.Command, args []string, _ string) ([]string, cobra.ShellCompDirective) { if len(args) == 0 { // We do file completion, in case the plugin is local return nil, cobra.ShellCompDirectiveDefault } // No more completion once the plugin path has been specified return noMoreArgsComp() }, PreRunE: func(_ *cobra.Command, args []string) error { return o.complete(args) }, RunE: func(_ *cobra.Command, _ []string) error { return o.run(out) }, } cmd.Flags().StringVar(&o.version, "version", "", "specify a version constraint. If this is not specified, the latest version is installed") cmd.Flags().BoolVar(&o.verify, "verify", true, "verify the plugin signature before installing") cmd.Flags().StringVar(&o.keyring, "keyring", defaultKeyring(), "location of public keys used for verification") // Add OCI-specific flags cmd.Flags().StringVar(&o.certFile, "cert-file", "", "identify registry client using this SSL certificate file") cmd.Flags().StringVar(&o.keyFile, "key-file", "", "identify registry client using this SSL key file") cmd.Flags().StringVar(&o.caFile, "ca-file", "", "verify certificates of HTTPS-enabled servers using this CA bundle") cmd.Flags().BoolVar(&o.insecureSkipTLSVerify, "insecure-skip-tls-verify", false, "skip tls certificate checks for the plugin download") cmd.Flags().BoolVar(&o.plainHTTP, "plain-http", false, "use insecure HTTP connections for the plugin download") cmd.Flags().StringVar(&o.username, "username", "", "registry username") cmd.Flags().StringVar(&o.password, "password", "", "registry password") return cmd } func (o *pluginInstallOptions) complete(args []string) error { o.source = args[0] return nil } func (o *pluginInstallOptions) newInstallerForSource() (installer.Installer, error) { // Check if source is an OCI registry reference if strings.HasPrefix(o.source, fmt.Sprintf("%s://", registry.OCIScheme)) { // Build getter options for OCI options := []getter.Option{ getter.WithTLSClientConfig(o.certFile, o.keyFile, o.caFile), getter.WithInsecureSkipVerifyTLS(o.insecureSkipTLSVerify), getter.WithPlainHTTP(o.plainHTTP), getter.WithBasicAuth(o.username, o.password), } return installer.NewOCIInstaller(o.source, options...) } // For non-OCI sources, use the original logic return installer.NewForSource(o.source, o.version) } func (o *pluginInstallOptions) run(out io.Writer) error { i, err := o.newInstallerForSource() if err != nil { return err } // Determine if we should verify based on installer type and flags shouldVerify := o.verify // Check if this is a local directory installation (for development) if localInst, ok := i.(*installer.LocalInstaller); ok && !localInst.SupportsVerification() { // Local directory installations are allowed without verification shouldVerify = false fmt.Fprintf(out, "Installing plugin from local directory (development mode)\n") } else if shouldVerify { // For remote installations, check if verification is supported if verifier, ok := i.(installer.Verifier); !ok || !verifier.SupportsVerification() { return fmt.Errorf("plugin source does not support verification. Use --verify=false to skip verification") } } else { // User explicitly disabled verification fmt.Fprintf(out, "WARNING: Skipping plugin signature verification\n") } // Set up installation options opts := installer.Options{ Verify: shouldVerify, Keyring: o.keyring, } // If verify is requested, show verification output if shouldVerify { fmt.Fprintf(out, "Verifying plugin signature...\n") } // Install the plugin with options verifyResult, err := installer.InstallWithOptions(i, opts) if err != nil { return err } // If verification was successful, show the details if verifyResult != nil { for _, signer := range verifyResult.SignedBy { fmt.Fprintf(out, "Signed by: %s\n", signer) } fmt.Fprintf(out, "Using Key With Fingerprint: %s\n", verifyResult.Fingerprint) fmt.Fprintf(out, "Plugin Hash Verified: %s\n", verifyResult.FileHash) } slog.Debug("loading plugin", "path", i.Path()) p, err := plugin.LoadDir(i.Path()) if err != nil { return fmt.Errorf("plugin is installed but unusable: %w", err) } if err := runHook(p, plugin.Install); err != nil { return err } fmt.Fprintf(out, "Installed plugin: %s\n", p.Metadata().Name) return nil }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/get_values.go
pkg/cmd/get_values.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "io" "log" "github.com/spf13/cobra" "helm.sh/helm/v4/pkg/action" "helm.sh/helm/v4/pkg/cli/output" "helm.sh/helm/v4/pkg/cmd/require" ) var getValuesHelp = ` This command downloads a values file for a given release. ` type valuesWriter struct { vals map[string]interface{} allValues bool } func newGetValuesCmd(cfg *action.Configuration, out io.Writer) *cobra.Command { var outfmt output.Format client := action.NewGetValues(cfg) cmd := &cobra.Command{ Use: "values RELEASE_NAME", Short: "download the values file for a named release", Long: getValuesHelp, Args: require.ExactArgs(1), ValidArgsFunction: func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { if len(args) != 0 { return noMoreArgsComp() } return compListReleases(toComplete, args, cfg) }, RunE: func(_ *cobra.Command, args []string) error { vals, err := client.Run(args[0]) if err != nil { return err } return outfmt.Write(out, &valuesWriter{vals, client.AllValues}) }, } f := cmd.Flags() f.IntVar(&client.Version, "revision", 0, "get the named release with revision") err := cmd.RegisterFlagCompletionFunc("revision", func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { if len(args) == 1 { return compListRevisions(toComplete, cfg, args[0]) } return nil, cobra.ShellCompDirectiveNoFileComp }) if err != nil { log.Fatal(err) } f.BoolVarP(&client.AllValues, "all", "a", false, "dump all (computed) values") bindOutputFlag(cmd, &outfmt) return cmd } func (v valuesWriter) WriteTable(out io.Writer) error { if v.allValues { fmt.Fprintln(out, "COMPUTED VALUES:") } else { fmt.Fprintln(out, "USER-SUPPLIED VALUES:") } return output.EncodeYAML(out, v.vals) } func (v valuesWriter) WriteJSON(out io.Writer) error { return output.EncodeJSON(out, v.vals) } func (v valuesWriter) WriteYAML(out io.Writer) error { return output.EncodeYAML(out, v.vals) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/root_test.go
pkg/cmd/root_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "bytes" "log/slog" "os" "path/filepath" "testing" "helm.sh/helm/v4/internal/test/ensure" "helm.sh/helm/v4/pkg/action" "helm.sh/helm/v4/pkg/helmpath" "helm.sh/helm/v4/pkg/helmpath/xdg" ) func TestRootCmd(t *testing.T) { defer resetEnv()() tests := []struct { name, args, cachePath, configPath, dataPath string envvars map[string]string }{ { name: "defaults", args: "env", }, { name: "with $XDG_CACHE_HOME set", args: "env", envvars: map[string]string{xdg.CacheHomeEnvVar: "/bar"}, cachePath: "/bar/helm", }, { name: "with $XDG_CONFIG_HOME set", args: "env", envvars: map[string]string{xdg.ConfigHomeEnvVar: "/bar"}, configPath: "/bar/helm", }, { name: "with $XDG_DATA_HOME set", args: "env", envvars: map[string]string{xdg.DataHomeEnvVar: "/bar"}, dataPath: "/bar/helm", }, { name: "with $HELM_CACHE_HOME set", args: "env", envvars: map[string]string{helmpath.CacheHomeEnvVar: "/foo/helm"}, cachePath: "/foo/helm", }, { name: "with $HELM_CONFIG_HOME set", args: "env", envvars: map[string]string{helmpath.ConfigHomeEnvVar: "/foo/helm"}, configPath: "/foo/helm", }, { name: "with $HELM_DATA_HOME set", args: "env", envvars: map[string]string{helmpath.DataHomeEnvVar: "/foo/helm"}, dataPath: "/foo/helm", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ensure.HelmHome(t) for k, v := range tt.envvars { t.Setenv(k, v) } if _, _, err := executeActionCommand(tt.args); err != nil { t.Fatalf("unexpected error: %s", err) } // NOTE(bacongobbler): we need to check here after calling ensure.HelmHome so we // load the proper paths after XDG_*_HOME is set if tt.cachePath == "" { tt.cachePath = filepath.Join(os.Getenv(xdg.CacheHomeEnvVar), "helm") } if tt.configPath == "" { tt.configPath = filepath.Join(os.Getenv(xdg.ConfigHomeEnvVar), "helm") } if tt.dataPath == "" { tt.dataPath = filepath.Join(os.Getenv(xdg.DataHomeEnvVar), "helm") } if helmpath.CachePath() != tt.cachePath { t.Errorf("expected cache path %q, got %q", tt.cachePath, helmpath.CachePath()) } if helmpath.ConfigPath() != tt.configPath { t.Errorf("expected config path %q, got %q", tt.configPath, helmpath.ConfigPath()) } if helmpath.DataPath() != tt.dataPath { t.Errorf("expected data path %q, got %q", tt.dataPath, helmpath.DataPath()) } }) } } func TestUnknownSubCmd(t *testing.T) { _, _, err := executeActionCommand("foobar") if err == nil || err.Error() != `unknown command "foobar" for "helm"` { t.Errorf("Expect unknown command error, got %q", err) } } // Need the release of Cobra following 1.0 to be able to disable // file completion on the root command. Until then, we cannot // because it would break 'helm help <TAB>' // // func TestRootFileCompletion(t *testing.T) { // checkFileCompletion(t, "", false) // } func TestRootCmdLogger(t *testing.T) { args := []string{} buf := new(bytes.Buffer) actionConfig := action.NewConfiguration() _, err := newRootCmdWithConfig(actionConfig, buf, args, SetupLogging) if err != nil { t.Errorf("expected no error, got: '%v'", err) } l1 := actionConfig.Logger() l2 := slog.Default() if l1.Handler() != l2.Handler() { t.Error("expected actionConfig logger to be the slog default logger") } }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/status_test.go
pkg/cmd/status_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "testing" "time" chart "helm.sh/helm/v4/pkg/chart/v2" "helm.sh/helm/v4/pkg/release/common" release "helm.sh/helm/v4/pkg/release/v1" ) func TestStatusCmd(t *testing.T) { releasesMockWithStatus := func(info *release.Info, hooks ...*release.Hook) []*release.Release { info.LastDeployed = time.Unix(1452902400, 0).UTC() return []*release.Release{{ Name: "flummoxed-chickadee", Namespace: "default", Info: info, Chart: &chart.Chart{Metadata: &chart.Metadata{Name: "name", Version: "1.2.3", AppVersion: "3.2.1"}}, Hooks: hooks, }} } tests := []cmdTestCase{{ name: "get status of a deployed release", cmd: "status flummoxed-chickadee", golden: "output/status.txt", rels: releasesMockWithStatus(&release.Info{ Status: common.StatusDeployed, }), }, { name: "get status of a deployed release, with desc", cmd: "status flummoxed-chickadee", golden: "output/status-with-desc.txt", rels: releasesMockWithStatus(&release.Info{ Status: common.StatusDeployed, Description: "Mock description", }), }, { name: "get status of a deployed release with notes", cmd: "status flummoxed-chickadee", golden: "output/status-with-notes.txt", rels: releasesMockWithStatus(&release.Info{ Status: common.StatusDeployed, Notes: "release notes", }), }, { name: "get status of a deployed release with notes in json", cmd: "status flummoxed-chickadee -o json", golden: "output/status.json", rels: releasesMockWithStatus(&release.Info{ Status: common.StatusDeployed, Notes: "release notes", }), }, { name: "get status of a deployed release with resources", cmd: "status flummoxed-chickadee", golden: "output/status-with-resources.txt", rels: releasesMockWithStatus( &release.Info{ Status: common.StatusDeployed, }, ), }, { name: "get status of a deployed release with resources in json", cmd: "status flummoxed-chickadee -o json", golden: "output/status-with-resources.json", rels: releasesMockWithStatus( &release.Info{ Status: common.StatusDeployed, }, ), }, { name: "get status of a deployed release with test suite", cmd: "status flummoxed-chickadee", golden: "output/status-with-test-suite.txt", rels: releasesMockWithStatus( &release.Info{ Status: common.StatusDeployed, }, &release.Hook{ Name: "never-run-test", Events: []release.HookEvent{release.HookTest}, }, &release.Hook{ Name: "passing-test", Events: []release.HookEvent{release.HookTest}, LastRun: release.HookExecution{ StartedAt: mustParseTime("2006-01-02T15:04:05Z"), CompletedAt: mustParseTime("2006-01-02T15:04:07Z"), Phase: release.HookPhaseSucceeded, }, }, &release.Hook{ Name: "failing-test", Events: []release.HookEvent{release.HookTest}, LastRun: release.HookExecution{ StartedAt: mustParseTime("2006-01-02T15:10:05Z"), CompletedAt: mustParseTime("2006-01-02T15:10:07Z"), Phase: release.HookPhaseFailed, }, }, &release.Hook{ Name: "passing-pre-install", Events: []release.HookEvent{release.HookPreInstall}, LastRun: release.HookExecution{ StartedAt: mustParseTime("2006-01-02T15:00:05Z"), CompletedAt: mustParseTime("2006-01-02T15:00:07Z"), Phase: release.HookPhaseSucceeded, }, }, ), }} runTestCmd(t, tests) } func mustParseTime(t string) time.Time { res, _ := time.Parse(time.RFC3339, t) return res } func TestStatusCompletion(t *testing.T) { rels := []*release.Release{ { Name: "athos", Namespace: "default", Info: &release.Info{ Status: common.StatusDeployed, }, Chart: &chart.Chart{ Metadata: &chart.Metadata{ Name: "Athos-chart", Version: "1.2.3", }, }, }, { Name: "porthos", Namespace: "default", Info: &release.Info{ Status: common.StatusFailed, }, Chart: &chart.Chart{ Metadata: &chart.Metadata{ Name: "Porthos-chart", Version: "111.222.333", }, }, }, { Name: "aramis", Namespace: "default", Info: &release.Info{ Status: common.StatusUninstalled, }, Chart: &chart.Chart{ Metadata: &chart.Metadata{ Name: "Aramis-chart", Version: "0.0.0", }, }, }, { Name: "dartagnan", Namespace: "gascony", Info: &release.Info{ Status: common.StatusUnknown, }, Chart: &chart.Chart{ Metadata: &chart.Metadata{ Name: "Dartagnan-chart", Version: "1.2.3-prerelease", }, }, }} tests := []cmdTestCase{{ name: "completion for status", cmd: "__complete status a", golden: "output/status-comp.txt", rels: rels, }, { name: "completion for status with too many arguments", cmd: "__complete status dartagnan ''", golden: "output/status-wrong-args-comp.txt", rels: rels, }, { name: "completion for status with global flag", cmd: "__complete status --debug a", golden: "output/status-comp.txt", rels: rels, }} runTestCmd(t, tests) } func TestStatusRevisionCompletion(t *testing.T) { revisionFlagCompletionTest(t, "status") } func TestStatusOutputCompletion(t *testing.T) { outputFlagCompletionTest(t, "status") } func TestStatusFileCompletion(t *testing.T) { checkFileCompletion(t, "status", false) checkFileCompletion(t, "status myrelease", false) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/search_repo.go
pkg/cmd/search_repo.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "bufio" "bytes" "errors" "fmt" "io" "log/slog" "os" "path/filepath" "strings" "github.com/Masterminds/semver/v3" "github.com/gosuri/uitable" "github.com/spf13/cobra" "helm.sh/helm/v4/pkg/cli/output" "helm.sh/helm/v4/pkg/cmd/search" "helm.sh/helm/v4/pkg/helmpath" "helm.sh/helm/v4/pkg/repo/v1" ) const searchRepoDesc = ` Search reads through all of the repositories configured on the system, and looks for matches. Search of these repositories uses the metadata stored on the system. It will display the latest stable versions of the charts found. If you specify the --devel flag, the output will include pre-release versions. If you want to search using a version constraint, use --version. Examples: # Search for stable release versions matching the keyword "nginx" $ helm search repo nginx # Search for release versions matching the keyword "nginx", including pre-release versions $ helm search repo nginx --devel # Search for the latest stable release for nginx-ingress with a major version of 1 $ helm search repo nginx-ingress --version ^1.0.0 Repositories are managed with 'helm repo' commands. ` // searchMaxScore suggests that any score higher than this is not considered a match. const searchMaxScore = 25 type searchRepoOptions struct { versions bool regexp bool devel bool version string maxColWidth uint repoFile string repoCacheDir string outputFormat output.Format failOnNoResult bool } func newSearchRepoCmd(out io.Writer) *cobra.Command { o := &searchRepoOptions{} cmd := &cobra.Command{ Use: "repo [keyword]", Short: "search repositories for a keyword in charts", Long: searchRepoDesc, RunE: func(_ *cobra.Command, args []string) error { o.repoFile = settings.RepositoryConfig o.repoCacheDir = settings.RepositoryCache return o.run(out, args) }, } f := cmd.Flags() f.BoolVarP(&o.regexp, "regexp", "r", false, "use regular expressions for searching repositories you have added") f.BoolVarP(&o.versions, "versions", "l", false, "show the long listing, with each version of each chart on its own line, for repositories you have added") f.BoolVar(&o.devel, "devel", false, "use development versions (alpha, beta, and release candidate releases), too. Equivalent to version '>0.0.0-0'. If --version is set, this is ignored") f.StringVar(&o.version, "version", "", "search using semantic versioning constraints on repositories you have added") f.UintVar(&o.maxColWidth, "max-col-width", 50, "maximum column width for output table") f.BoolVar(&o.failOnNoResult, "fail-on-no-result", false, "search fails if no results are found") bindOutputFlag(cmd, &o.outputFormat) return cmd } func (o *searchRepoOptions) run(out io.Writer, args []string) error { o.setupSearchedVersion() index, err := o.buildIndex() if err != nil { return err } var res []*search.Result if len(args) == 0 { res = index.All() } else { q := strings.Join(args, " ") res, err = index.Search(q, searchMaxScore, o.regexp) if err != nil { return err } } search.SortScore(res) data, err := o.applyConstraint(res) if err != nil { return err } return o.outputFormat.Write(out, &repoSearchWriter{data, o.maxColWidth, o.failOnNoResult}) } func (o *searchRepoOptions) setupSearchedVersion() { slog.Debug("original chart version", "version", o.version) if o.version != "" { return } if o.devel { // search for releases and prereleases (alpha, beta, and release candidate releases). slog.Debug("setting version to >0.0.0-0") o.version = ">0.0.0-0" } else { // search only for stable releases, prerelease versions will be skipped slog.Debug("setting version to >0.0.0") o.version = ">0.0.0" } } func (o *searchRepoOptions) applyConstraint(res []*search.Result) ([]*search.Result, error) { if o.version == "" { return res, nil } constraint, err := semver.NewConstraint(o.version) if err != nil { return res, fmt.Errorf("an invalid version/constraint format: %w", err) } data := res[:0] foundNames := map[string]bool{} for _, r := range res { // if not returning all versions and already have found a result, // you're done! if !o.versions && foundNames[r.Name] { continue } v, err := semver.NewVersion(r.Chart.Version) if err != nil { continue } if constraint.Check(v) { data = append(data, r) foundNames[r.Name] = true } } return data, nil } func (o *searchRepoOptions) buildIndex() (*search.Index, error) { // Load the repositories.yaml rf, err := repo.LoadFile(o.repoFile) if isNotExist(err) || len(rf.Repositories) == 0 { return nil, errors.New("no repositories configured") } i := search.NewIndex() for _, re := range rf.Repositories { n := re.Name f := filepath.Join(o.repoCacheDir, helmpath.CacheIndexFile(n)) ind, err := repo.LoadIndexFile(f) if err != nil { slog.Warn("repo is corrupt or missing", slog.String("repo", n), slog.Any("error", err)) continue } i.AddRepo(n, ind, o.versions || len(o.version) > 0) } return i, nil } type repoChartElement struct { Name string `json:"name"` Version string `json:"version"` AppVersion string `json:"app_version"` Description string `json:"description"` } type repoSearchWriter struct { results []*search.Result columnWidth uint failOnNoResult bool } func (r *repoSearchWriter) WriteTable(out io.Writer) error { if len(r.results) == 0 { // Fail if no results found and --fail-on-no-result is enabled if r.failOnNoResult { return fmt.Errorf("no results found") } _, err := out.Write([]byte("No results found\n")) if err != nil { return fmt.Errorf("unable to write results: %s", err) } return nil } table := uitable.New() table.MaxColWidth = r.columnWidth table.AddRow("NAME", "CHART VERSION", "APP VERSION", "DESCRIPTION") for _, r := range r.results { table.AddRow(r.Name, r.Chart.Version, r.Chart.AppVersion, r.Chart.Description) } return output.EncodeTable(out, table) } func (r *repoSearchWriter) WriteJSON(out io.Writer) error { return r.encodeByFormat(out, output.JSON) } func (r *repoSearchWriter) WriteYAML(out io.Writer) error { return r.encodeByFormat(out, output.YAML) } func (r *repoSearchWriter) encodeByFormat(out io.Writer, format output.Format) error { // Fail if no results found and --fail-on-no-result is enabled if len(r.results) == 0 && r.failOnNoResult { return fmt.Errorf("no results found") } // Initialize the array so no results returns an empty array instead of null chartList := make([]repoChartElement, 0, len(r.results)) for _, r := range r.results { chartList = append(chartList, repoChartElement{r.Name, r.Chart.Version, r.Chart.AppVersion, r.Chart.Description}) } switch format { case output.JSON: return output.EncodeJSON(out, chartList) case output.YAML: return output.EncodeYAML(out, chartList) default: // Because this is a non-exported function and only called internally by // WriteJSON and WriteYAML, we shouldn't get invalid types return nil } } // Provides the list of charts that are part of the specified repo, and that starts with 'prefix'. func compListChartsOfRepo(repoName string, prefix string) []string { var charts []string path := filepath.Join(settings.RepositoryCache, helmpath.CacheChartsFile(repoName)) content, err := os.ReadFile(path) if err == nil { scanner := bufio.NewScanner(bytes.NewReader(content)) for scanner.Scan() { fullName := fmt.Sprintf("%s/%s", repoName, scanner.Text()) if strings.HasPrefix(fullName, prefix) { charts = append(charts, fullName) } } return charts } if isNotExist(err) { // If there is no cached charts file, fallback to the full index file. // This is much slower but can happen after the caching feature is first // installed but before the user does a 'helm repo update' to generate the // first cached charts file. path = filepath.Join(settings.RepositoryCache, helmpath.CacheIndexFile(repoName)) if indexFile, err := repo.LoadIndexFile(path); err == nil { for name := range indexFile.Entries { fullName := fmt.Sprintf("%s/%s", repoName, name) if strings.HasPrefix(fullName, prefix) { charts = append(charts, fullName) } } return charts } } return []string{} } // Provide dynamic auto-completion for commands that operate on charts (e.g., helm show) // When true, the includeFiles argument indicates that completion should include local files (e.g., local charts) func compListCharts(toComplete string, includeFiles bool) ([]string, cobra.ShellCompDirective) { cobra.CompDebugln(fmt.Sprintf("compListCharts with toComplete %s", toComplete), settings.Debug) noSpace := false noFile := false var completions []string // First check completions for repos repos := compListRepos("", nil) for _, repoInfo := range repos { // Split name from description repoInfo := strings.Split(repoInfo, "\t") repo := repoInfo[0] repoDesc := "" if len(repoInfo) > 1 { repoDesc = repoInfo[1] } repoWithSlash := fmt.Sprintf("%s/", repo) if strings.HasPrefix(toComplete, repoWithSlash) { // Must complete with charts within the specified repo. // Don't filter on toComplete to allow for shell fuzzy matching completions = append(completions, compListChartsOfRepo(repo, "")...) noSpace = false break } else if strings.HasPrefix(repo, toComplete) { // Must complete the repo name with the slash, followed by the description completions = append(completions, fmt.Sprintf("%s\t%s", repoWithSlash, repoDesc)) noSpace = true } } cobra.CompDebugln(fmt.Sprintf("Completions after repos: %v", completions), settings.Debug) // Now handle completions for url prefixes for _, url := range []string{"oci://\tChart OCI prefix", "https://\tChart URL prefix", "http://\tChart URL prefix", "file://\tChart local URL prefix"} { if strings.HasPrefix(toComplete, url) { // The user already put in the full url prefix; we don't have // anything to add, but make sure the shell does not default // to file completion since we could be returning an empty array. noFile = true noSpace = true } else if strings.HasPrefix(url, toComplete) { // We are completing a url prefix completions = append(completions, url) noSpace = true } } cobra.CompDebugln(fmt.Sprintf("Completions after urls: %v", completions), settings.Debug) // Finally, provide file completion if we need to. // We only do this if: // 1- There are other completions found (if there are no completions, // the shell will do file completion itself) // 2- If there is some input from the user (or else we will end up // listing the entire content of the current directory which will // be too many choices for the user to find the real repos) if includeFiles && len(completions) > 0 && len(toComplete) > 0 { if files, err := os.ReadDir("."); err == nil { for _, file := range files { if strings.HasPrefix(file.Name(), toComplete) { // We are completing a file prefix completions = append(completions, file.Name()) } } } } cobra.CompDebugln(fmt.Sprintf("Completions after files: %v", completions), settings.Debug) // If the user didn't provide any input to completion, // we provide a hint that a path can also be used if includeFiles && len(toComplete) == 0 { completions = append(completions, "./\tRelative path prefix to local chart", "/\tAbsolute path prefix to local chart") } cobra.CompDebugln(fmt.Sprintf("Completions after checking empty input: %v", completions), settings.Debug) directive := cobra.ShellCompDirectiveDefault if noFile { directive = directive | cobra.ShellCompDirectiveNoFileComp } if noSpace { directive = directive | cobra.ShellCompDirectiveNoSpace } if !includeFiles { // If we should not include files in the completions, // we should disable file completion directive = directive | cobra.ShellCompDirectiveNoFileComp } return completions, directive }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/plugin_uninstall_test.go
pkg/cmd/plugin_uninstall_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "os" "path/filepath" "testing" "helm.sh/helm/v4/internal/plugin" "helm.sh/helm/v4/internal/test/ensure" "helm.sh/helm/v4/pkg/cli" ) func TestPluginUninstallCleansUpVersionedFiles(t *testing.T) { ensure.HelmHome(t) // Create a fake plugin directory structure in a temp directory pluginsDir := t.TempDir() t.Setenv("HELM_PLUGINS", pluginsDir) // Create a new settings instance that will pick up the environment variable testSettings := cli.New() pluginName := "test-plugin" // Create plugin directory pluginDir := filepath.Join(pluginsDir, pluginName) if err := os.MkdirAll(pluginDir, 0755); err != nil { t.Fatal(err) } // Create plugin.yaml pluginYAML := `name: test-plugin version: 1.2.3 description: Test plugin command: $HELM_PLUGIN_DIR/test-plugin ` if err := os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(pluginYAML), 0644); err != nil { t.Fatal(err) } // Create versioned tarball and provenance files tarballFile := filepath.Join(pluginsDir, "test-plugin-1.2.3.tgz") provFile := filepath.Join(pluginsDir, "test-plugin-1.2.3.tgz.prov") otherVersionTarball := filepath.Join(pluginsDir, "test-plugin-2.0.0.tgz") if err := os.WriteFile(tarballFile, []byte("fake tarball"), 0644); err != nil { t.Fatal(err) } if err := os.WriteFile(provFile, []byte("fake provenance"), 0644); err != nil { t.Fatal(err) } // Create another version that should NOT be removed if err := os.WriteFile(otherVersionTarball, []byte("other version"), 0644); err != nil { t.Fatal(err) } // Load the plugin p, err := plugin.LoadDir(pluginDir) if err != nil { t.Fatal(err) } // Create a test uninstall function that uses our test settings testUninstallPlugin := func(plugin plugin.Plugin) error { if err := os.RemoveAll(plugin.Dir()); err != nil { return err } // Clean up versioned tarball and provenance files from test HELM_PLUGINS directory pluginName := plugin.Metadata().Name pluginVersion := plugin.Metadata().Version testPluginsDir := testSettings.PluginsDirectory // Remove versioned files: plugin-name-version.tgz and plugin-name-version.tgz.prov if pluginVersion != "" { versionedBasename := fmt.Sprintf("%s-%s.tgz", pluginName, pluginVersion) // Remove tarball file tarballPath := filepath.Join(testPluginsDir, versionedBasename) if _, err := os.Stat(tarballPath); err == nil { if err := os.Remove(tarballPath); err != nil { t.Logf("failed to remove tarball file: %v", err) } } // Remove provenance file provPath := filepath.Join(testPluginsDir, versionedBasename+".prov") if _, err := os.Stat(provPath); err == nil { if err := os.Remove(provPath); err != nil { t.Logf("failed to remove provenance file: %v", err) } } } // Skip runHook in test return nil } // Verify files exist before uninstall if _, err := os.Stat(tarballFile); os.IsNotExist(err) { t.Fatal("tarball file should exist before uninstall") } if _, err := os.Stat(provFile); os.IsNotExist(err) { t.Fatal("provenance file should exist before uninstall") } if _, err := os.Stat(otherVersionTarball); os.IsNotExist(err) { t.Fatal("other version tarball should exist before uninstall") } // Uninstall the plugin if err := testUninstallPlugin(p); err != nil { t.Fatal(err) } // Verify plugin directory is removed if _, err := os.Stat(pluginDir); !os.IsNotExist(err) { t.Error("plugin directory should be removed") } // Verify only exact version files are removed if _, err := os.Stat(tarballFile); !os.IsNotExist(err) { t.Error("versioned tarball file should be removed") } if _, err := os.Stat(provFile); !os.IsNotExist(err) { t.Error("versioned provenance file should be removed") } // Verify other version files are NOT removed if _, err := os.Stat(otherVersionTarball); os.IsNotExist(err) { t.Error("other version tarball should NOT be removed") } }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/repo_update_test.go
pkg/cmd/repo_update_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "bytes" "fmt" "io" "os" "path/filepath" "strings" "testing" "helm.sh/helm/v4/internal/test/ensure" "helm.sh/helm/v4/pkg/getter" "helm.sh/helm/v4/pkg/repo/v1" "helm.sh/helm/v4/pkg/repo/v1/repotest" ) func TestUpdateCmd(t *testing.T) { var out bytes.Buffer // Instead of using the HTTP updater, we provide our own for this test. // The TestUpdateCharts test verifies the HTTP behavior independently. updater := func(repos []*repo.ChartRepository, out io.Writer) error { for _, re := range repos { fmt.Fprintln(out, re.Config.Name) } return nil } o := &repoUpdateOptions{ update: updater, repoFile: "testdata/repositories.yaml", } if err := o.run(&out); err != nil { t.Fatal(err) } if got := out.String(); !strings.Contains(got, "charts") || !strings.Contains(got, "firstexample") || !strings.Contains(got, "secondexample") { t.Errorf("Expected 'charts', 'firstexample' and 'secondexample' but got %q", got) } } func TestUpdateCmdMultiple(t *testing.T) { var out bytes.Buffer // Instead of using the HTTP updater, we provide our own for this test. // The TestUpdateCharts test verifies the HTTP behavior independently. updater := func(repos []*repo.ChartRepository, out io.Writer) error { for _, re := range repos { fmt.Fprintln(out, re.Config.Name) } return nil } o := &repoUpdateOptions{ update: updater, repoFile: "testdata/repositories.yaml", names: []string{"firstexample", "charts"}, } if err := o.run(&out); err != nil { t.Fatal(err) } if got := out.String(); !strings.Contains(got, "charts") || !strings.Contains(got, "firstexample") || strings.Contains(got, "secondexample") { t.Errorf("Expected 'charts' and 'firstexample' but not 'secondexample' but got %q", got) } } func TestUpdateCmdInvalid(t *testing.T) { var out bytes.Buffer // Instead of using the HTTP updater, we provide our own for this test. // The TestUpdateCharts test verifies the HTTP behavior independently. updater := func(repos []*repo.ChartRepository, out io.Writer) error { for _, re := range repos { fmt.Fprintln(out, re.Config.Name) } return nil } o := &repoUpdateOptions{ update: updater, repoFile: "testdata/repositories.yaml", names: []string{"firstexample", "invalid"}, } if err := o.run(&out); err == nil { t.Fatal("expected error but did not get one") } } func TestUpdateCustomCacheCmd(t *testing.T) { rootDir := t.TempDir() cachePath := filepath.Join(rootDir, "updcustomcache") os.Mkdir(cachePath, os.ModePerm) ts := repotest.NewTempServer( t, repotest.WithChartSourceGlob("testdata/testserver/*.*"), ) defer ts.Stop() o := &repoUpdateOptions{ update: updateCharts, repoFile: filepath.Join(ts.Root(), "repositories.yaml"), repoCache: cachePath, } b := io.Discard if err := o.run(b); err != nil { t.Fatal(err) } if _, err := os.Stat(filepath.Join(cachePath, "test-index.yaml")); err != nil { t.Fatalf("error finding created index file in custom cache: %v", err) } } func TestUpdateCharts(t *testing.T) { defer resetEnv()() ensure.HelmHome(t) ts := repotest.NewTempServer(t, repotest.WithChartSourceGlob("testdata/testserver/*.*"), ) defer ts.Stop() r, err := repo.NewChartRepository(&repo.Entry{ Name: "charts", URL: ts.URL(), }, getter.All(settings)) if err != nil { t.Error(err) } b := bytes.NewBuffer(nil) updateCharts([]*repo.ChartRepository{r}, b) got := b.String() if strings.Contains(got, "Unable to get an update") { t.Errorf("Failed to get a repo: %q", got) } if !strings.Contains(got, "Update Complete.") { t.Error("Update was not successful") } } func TestRepoUpdateFileCompletion(t *testing.T) { checkFileCompletion(t, "repo update", false) checkFileCompletion(t, "repo update repo1", false) } func TestUpdateChartsFailWithError(t *testing.T) { defer resetEnv()() ensure.HelmHome(t) ts := repotest.NewTempServer( t, repotest.WithChartSourceGlob("testdata/testserver/*.*"), ) defer ts.Stop() var invalidURL = ts.URL() + "55" r1, err := repo.NewChartRepository(&repo.Entry{ Name: "charts", URL: invalidURL, }, getter.All(settings)) if err != nil { t.Error(err) } r2, err := repo.NewChartRepository(&repo.Entry{ Name: "charts", URL: invalidURL, }, getter.All(settings)) if err != nil { t.Error(err) } b := bytes.NewBuffer(nil) err = updateCharts([]*repo.ChartRepository{r1, r2}, b) if err == nil { t.Error("Repo update should return error because update of repository fails and 'fail-on-repo-update-fail' flag set") return } var expectedErr = "failed to update the following repositories" var receivedErr = err.Error() if !strings.Contains(receivedErr, expectedErr) { t.Errorf("Expected error (%s) but got (%s) instead", expectedErr, receivedErr) } if !strings.Contains(receivedErr, invalidURL) { t.Errorf("Expected invalid URL (%s) in error message but got (%s) instead", invalidURL, receivedErr) } got := b.String() if !strings.Contains(got, "Unable to get an update") { t.Errorf("Repo should have failed update but instead got: %q", got) } if strings.Contains(got, "Update Complete.") { t.Error("Update was not successful and should return error message because 'fail-on-repo-update-fail' flag set") } }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/env_test.go
pkg/cmd/env_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "testing" ) func TestEnv(t *testing.T) { tests := []cmdTestCase{{ name: "completion for env", cmd: "__complete env ''", golden: "output/env-comp.txt", }} runTestCmd(t, tests) } func TestEnvFileCompletion(t *testing.T) { checkFileCompletion(t, "env", false) checkFileCompletion(t, "env HELM_BIN", false) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/plugin_test.go
pkg/cmd/plugin_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "bytes" "fmt" "os" "runtime" "strings" "testing" "github.com/spf13/cobra" "github.com/spf13/pflag" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" release "helm.sh/helm/v4/pkg/release/v1" ) func TestManuallyProcessArgs(t *testing.T) { input := []string{ "--debug", "--foo", "bar", "--kubeconfig=/home/foo", "--kubeconfig", "/home/foo", "--kube-context=test1", "--kube-context", "test1", "--kube-as-user", "pikachu", "--kube-as-group", "teatime", "--kube-as-group", "admins", "-n=test2", "-n", "test2", "--namespace=test2", "--namespace", "test2", "--home=/tmp", "command", } expectKnown := []string{ "--debug", "--kubeconfig=/home/foo", "--kubeconfig", "/home/foo", "--kube-context=test1", "--kube-context", "test1", "--kube-as-user", "pikachu", "--kube-as-group", "teatime", "--kube-as-group", "admins", "-n=test2", "-n", "test2", "--namespace=test2", "--namespace", "test2", } expectUnknown := []string{ "--foo", "bar", "--home=/tmp", "command", } known, unknown := manuallyProcessArgs(input) for i, k := range known { if k != expectKnown[i] { t.Errorf("expected known flag %d to be %q, got %q", i, expectKnown[i], k) } } for i, k := range unknown { if k != expectUnknown[i] { t.Errorf("expected unknown flag %d to be %q, got %q", i, expectUnknown[i], k) } } } func TestLoadCLIPlugins(t *testing.T) { settings.PluginsDirectory = "testdata/helmhome/helm/plugins" settings.RepositoryConfig = "testdata/helmhome/helm/repositories.yaml" settings.RepositoryCache = "testdata/helmhome/helm/repository" var ( out bytes.Buffer cmd cobra.Command ) loadCLIPlugins(&cmd, &out) fullEnvOutput := strings.Join([]string{ "HELM_PLUGIN_NAME=fullenv", "HELM_PLUGIN_DIR=testdata/helmhome/helm/plugins/fullenv", "HELM_PLUGINS=testdata/helmhome/helm/plugins", "HELM_REPOSITORY_CONFIG=testdata/helmhome/helm/repositories.yaml", "HELM_REPOSITORY_CACHE=testdata/helmhome/helm/repository", fmt.Sprintf("HELM_BIN=%s", os.Args[0]), }, "\n") + "\n" // Test that the YAML file was correctly converted to a command. tests := []struct { use string short string long string expect string args []string code int }{ {"args", "echo args", "This echos args", "-a -b -c\n", []string{"-a", "-b", "-c"}, 0}, {"echo", "echo stuff", "This echos stuff", "hello\n", []string{}, 0}, {"env", "env stuff", "show the env", "HELM_PLUGIN_NAME=env\n", []string{}, 0}, {"exitwith", "exitwith code", "This exits with the specified exit code", "", []string{"2"}, 2}, {"fullenv", "show env vars", "show all env vars", fullEnvOutput, []string{}, 0}, } pluginCmds := cmd.Commands() require.Len(t, pluginCmds, len(tests), "Expected %d plugins, got %d", len(tests), len(pluginCmds)) for i := range pluginCmds { out.Reset() tt := tests[i] pluginCmd := pluginCmds[i] t.Run(fmt.Sprintf("%s-%d", pluginCmd.Name(), i), func(t *testing.T) { out.Reset() if pluginCmd.Use != tt.use { t.Errorf("%d: Expected Use=%q, got %q", i, tt.use, pluginCmd.Use) } if pluginCmd.Short != tt.short { t.Errorf("%d: Expected Use=%q, got %q", i, tt.short, pluginCmd.Short) } if pluginCmd.Long != tt.long { t.Errorf("%d: Expected Use=%q, got %q", i, tt.long, pluginCmd.Long) } // Currently, plugins assume a Linux subsystem. Skip the execution // tests until this is fixed if runtime.GOOS != "windows" { if err := pluginCmd.RunE(pluginCmd, tt.args); err != nil { if tt.code > 0 { cerr, ok := err.(CommandError) if !ok { t.Errorf("Expected %s to return pluginError: got %v(%T)", tt.use, err, err) } if cerr.ExitCode != tt.code { t.Errorf("Expected %s to return %d: got %d", tt.use, tt.code, cerr.ExitCode) } } else { t.Errorf("Error running %s: %+v", tt.use, err) } } assert.Equal(t, tt.expect, out.String(), "expected output for %q", tt.use) } }) } } func TestLoadPluginsWithSpace(t *testing.T) { settings.PluginsDirectory = "testdata/helm home with space/helm/plugins" settings.RepositoryConfig = "testdata/helm home with space/helm/repositories.yaml" settings.RepositoryCache = "testdata/helm home with space/helm/repository" var ( out bytes.Buffer cmd cobra.Command ) loadCLIPlugins(&cmd, &out) envs := strings.Join([]string{ "fullenv", "testdata/helm home with space/helm/plugins/fullenv", "testdata/helm home with space/helm/plugins", "testdata/helm home with space/helm/repositories.yaml", "testdata/helm home with space/helm/repository", os.Args[0], }, "\n") // Test that the YAML file was correctly converted to a command. tests := []struct { use string short string long string expect string args []string code int }{ {"fullenv", "show env vars", "show all env vars", envs + "\n", []string{}, 0}, } plugins := cmd.Commands() if len(plugins) != len(tests) { t.Fatalf("Expected %d plugins, got %d", len(tests), len(plugins)) } for i := range plugins { out.Reset() tt := tests[i] pp := plugins[i] if pp.Use != tt.use { t.Errorf("%d: Expected Use=%q, got %q", i, tt.use, pp.Use) } if pp.Short != tt.short { t.Errorf("%d: Expected Use=%q, got %q", i, tt.short, pp.Short) } if pp.Long != tt.long { t.Errorf("%d: Expected Use=%q, got %q", i, tt.long, pp.Long) } // Currently, plugins assume a Linux subsystem. Skip the execution // tests until this is fixed if runtime.GOOS != "windows" { if err := pp.RunE(pp, tt.args); err != nil { if tt.code > 0 { cerr, ok := err.(CommandError) if !ok { t.Errorf("Expected %s to return pluginError: got %v(%T)", tt.use, err, err) } if cerr.ExitCode != tt.code { t.Errorf("Expected %s to return %d: got %d", tt.use, tt.code, cerr.ExitCode) } } else { t.Errorf("Error running %s: %+v", tt.use, err) } } assert.Equal(t, tt.expect, out.String(), "expected output for %s", tt.use) } } } type staticCompletionDetails struct { use string validArgs []string flags []string next []staticCompletionDetails } func TestLoadCLIPluginsForCompletion(t *testing.T) { settings.PluginsDirectory = "testdata/helmhome/helm/plugins" var out bytes.Buffer cmd := &cobra.Command{ Use: "completion", } loadCLIPlugins(cmd, &out) tests := []staticCompletionDetails{ {"args", []string{}, []string{}, []staticCompletionDetails{}}, {"echo", []string{}, []string{}, []staticCompletionDetails{}}, {"env", []string{}, []string{"global"}, []staticCompletionDetails{ {"list", []string{}, []string{"a", "all", "log"}, []staticCompletionDetails{}}, {"remove", []string{"all", "one"}, []string{}, []staticCompletionDetails{}}, }}, {"exitwith", []string{}, []string{}, []staticCompletionDetails{ {"code", []string{}, []string{"a", "b"}, []staticCompletionDetails{}}, }}, {"fullenv", []string{}, []string{"q", "z"}, []staticCompletionDetails{ {"empty", []string{}, []string{}, []staticCompletionDetails{}}, {"full", []string{}, []string{}, []staticCompletionDetails{ {"less", []string{}, []string{"a", "all"}, []staticCompletionDetails{}}, {"more", []string{"one", "two"}, []string{"b", "ball"}, []staticCompletionDetails{}}, }}, }}, } checkCommand(t, cmd.Commands(), tests) } func checkCommand(t *testing.T, plugins []*cobra.Command, tests []staticCompletionDetails) { t.Helper() require.Len(t, plugins, len(tests), "Expected commands %v, got %v", tests, plugins) is := assert.New(t) for i := range plugins { pp := plugins[i] tt := tests[i] is.Equal(pp.Use, tt.use, "Expected Use=%q, got %q", tt.use, pp.Use) targs := tt.validArgs pargs := pp.ValidArgs is.ElementsMatch(targs, pargs) tflags := tt.flags var pflags []string pp.LocalFlags().VisitAll(func(flag *pflag.Flag) { pflags = append(pflags, flag.Name) if len(flag.Shorthand) > 0 && flag.Shorthand != flag.Name { pflags = append(pflags, flag.Shorthand) } }) is.ElementsMatch(tflags, pflags) // Check the next level checkCommand(t, pp.Commands(), tt.next) } } func TestPluginDynamicCompletion(t *testing.T) { tests := []cmdTestCase{{ name: "completion for plugin", cmd: "__complete args ''", golden: "output/plugin_args_comp.txt", rels: []*release.Release{}, }, { name: "completion for plugin with flag", cmd: "__complete args --myflag ''", golden: "output/plugin_args_flag_comp.txt", rels: []*release.Release{}, }, { name: "completion for plugin with global flag", cmd: "__complete args --namespace mynamespace ''", golden: "output/plugin_args_ns_comp.txt", rels: []*release.Release{}, }, { name: "completion for plugin with multiple args", cmd: "__complete args --myflag --namespace mynamespace start", golden: "output/plugin_args_many_args_comp.txt", rels: []*release.Release{}, }, { name: "completion for plugin no directive", cmd: "__complete echo -n mynamespace ''", golden: "output/plugin_echo_no_directive.txt", rels: []*release.Release{}, }} for _, test := range tests { settings.PluginsDirectory = "testdata/helmhome/helm/plugins" runTestCmd(t, []cmdTestCase{test}) } } func TestLoadCLIPlugins_HelmNoPlugins(t *testing.T) { settings.PluginsDirectory = "testdata/helmhome/helm/plugins" settings.RepositoryConfig = "testdata/helmhome/helm/repository" t.Setenv("HELM_NO_PLUGINS", "1") out := bytes.NewBuffer(nil) cmd := &cobra.Command{} loadCLIPlugins(cmd, out) plugins := cmd.Commands() if len(plugins) != 0 { t.Fatalf("Expected 0 plugins, got %d", len(plugins)) } } func TestPluginCmdsCompletion(t *testing.T) { tests := []cmdTestCase{{ name: "completion for plugin update", cmd: "__complete plugin update ''", golden: "output/plugin_list_comp.txt", rels: []*release.Release{}, }, { name: "completion for plugin update, no filter", cmd: "__complete plugin update full", golden: "output/plugin_list_comp.txt", rels: []*release.Release{}, }, { name: "completion for plugin update repetition", cmd: "__complete plugin update args ''", golden: "output/plugin_repeat_comp.txt", rels: []*release.Release{}, }, { name: "completion for plugin uninstall", cmd: "__complete plugin uninstall ''", golden: "output/plugin_list_comp.txt", rels: []*release.Release{}, }, { name: "completion for plugin uninstall, no filter", cmd: "__complete plugin uninstall full", golden: "output/plugin_list_comp.txt", rels: []*release.Release{}, }, { name: "completion for plugin uninstall repetition", cmd: "__complete plugin uninstall args ''", golden: "output/plugin_repeat_comp.txt", rels: []*release.Release{}, }, { name: "completion for plugin list", cmd: "__complete plugin list ''", golden: "output/empty_nofile_comp.txt", rels: []*release.Release{}, }, { name: "completion for plugin install no args", cmd: "__complete plugin install ''", golden: "output/empty_default_comp.txt", rels: []*release.Release{}, }, { name: "completion for plugin install one arg", cmd: "__complete plugin list /tmp ''", golden: "output/empty_nofile_comp.txt", rels: []*release.Release{}, }, {}} for _, test := range tests { settings.PluginsDirectory = "testdata/helmhome/helm/plugins" runTestCmd(t, []cmdTestCase{test}) } } func TestPluginFileCompletion(t *testing.T) { checkFileCompletion(t, "plugin", false) } func TestPluginInstallFileCompletion(t *testing.T) { checkFileCompletion(t, "plugin install", true) checkFileCompletion(t, "plugin install mypath", false) } func TestPluginListFileCompletion(t *testing.T) { checkFileCompletion(t, "plugin list", false) } func TestPluginUninstallFileCompletion(t *testing.T) { checkFileCompletion(t, "plugin uninstall", false) checkFileCompletion(t, "plugin uninstall myplugin", false) } func TestPluginUpdateFileCompletion(t *testing.T) { checkFileCompletion(t, "plugin update", false) checkFileCompletion(t, "plugin update myplugin", false) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/pull_test.go
pkg/cmd/pull_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "net/http" "net/http/httptest" "os" "path/filepath" "testing" "helm.sh/helm/v4/pkg/repo/v1/repotest" ) func TestPullCmd(t *testing.T) { srv := repotest.NewTempServer( t, repotest.WithChartSourceGlob("testdata/testcharts/*.tgz*"), ) defer srv.Stop() ociSrv, err := repotest.NewOCIServer(t, srv.Root()) if err != nil { t.Fatal(err) } ociSrv.Run(t) if err := srv.LinkIndices(); err != nil { t.Fatal(err) } helmTestKeyOut := "Signed by: Helm Testing (This key should only be used for testing. DO NOT TRUST.) <helm-testing@helm.sh>\n" + "Using Key With Fingerprint: 5E615389B53CA37F0EE60BD3843BBF981FC18762\n" + "Chart Hash Verified: " // all flags will get "-d outdir" appended. tests := []struct { name string args string existFile string existDir string wantError bool wantErrorMsg string failExpect string expectFile string expectDir bool expectVerify bool expectSha string }{ { name: "Basic chart fetch", args: "test/signtest", expectFile: "./signtest-0.1.0.tgz", }, { name: "Chart fetch with version", args: "test/signtest --version=0.1.0", expectFile: "./signtest-0.1.0.tgz", }, { name: "Fail chart fetch with non-existent version", args: "test/signtest --version=99.1.0", wantError: true, failExpect: "no such chart", }, { name: "Fail fetching non-existent chart", args: "test/nosuchthing", failExpect: "Failed to fetch", wantError: true, }, { name: "Fetch and verify", args: "test/signtest --verify --keyring testdata/helm-test-key.pub", expectFile: "./signtest-0.1.0.tgz", expectVerify: true, expectSha: "sha256:e5ef611620fb97704d8751c16bab17fedb68883bfb0edc76f78a70e9173f9b55", }, { name: "Fetch and fail verify", args: "test/reqtest --verify --keyring testdata/helm-test-key.pub", failExpect: "Failed to fetch provenance", wantError: true, }, { name: "Fetch and untar", args: "test/signtest --untar --untardir signtest", expectFile: "./signtest", expectDir: true, }, { name: "Fetch untar when file with same name existed", args: "test/test1 --untar --untardir test1", existFile: "test1/test1", wantError: true, wantErrorMsg: fmt.Sprintf("failed to untar: a file or directory with the name %s already exists", filepath.Join(srv.Root(), "test1", "test1")), }, { name: "Fetch untar when dir with same name existed", args: "test/test --untar --untardir test2", existDir: "test2/test", wantError: true, wantErrorMsg: fmt.Sprintf("failed to untar: a file or directory with the name %s already exists", filepath.Join(srv.Root(), "test2", "test")), }, { name: "Fetch, verify, untar", args: "test/signtest --verify --keyring=testdata/helm-test-key.pub --untar --untardir signtest2", expectFile: "./signtest2", expectDir: true, expectVerify: true, expectSha: "sha256:e5ef611620fb97704d8751c16bab17fedb68883bfb0edc76f78a70e9173f9b55", }, { name: "Chart fetch using repo URL", expectFile: "./signtest-0.1.0.tgz", args: "signtest --repo " + srv.URL(), }, { name: "Fail fetching non-existent chart on repo URL", args: "someChart --repo " + srv.URL(), failExpect: "Failed to fetch chart", wantError: true, }, { name: "Specific version chart fetch using repo URL", expectFile: "./signtest-0.1.0.tgz", args: "signtest --version=0.1.0 --repo " + srv.URL(), }, { name: "Specific version chart fetch using repo URL", args: "signtest --version=0.2.0 --repo " + srv.URL(), failExpect: "Failed to fetch chart version", wantError: true, }, { name: "Chart fetch using repo URL with untardir", args: "signtest --version=0.1.0 --untar --untardir repo-url-test --repo " + srv.URL(), expectFile: "./signtest", expectDir: true, }, { name: "Chart fetch using repo URL with untardir and previous pull", args: "signtest --version=0.1.0 --untar --untardir repo-url-test --repo " + srv.URL(), failExpect: "failed to untar", wantError: true, }, { name: "Fetch OCI Chart", args: fmt.Sprintf("oci://%s/u/ocitestuser/oci-dependent-chart --version 0.1.0", ociSrv.RegistryURL), expectFile: "./oci-dependent-chart-0.1.0.tgz", }, { name: "Fetch OCI Chart with untar", args: fmt.Sprintf("oci://%s/u/ocitestuser/oci-dependent-chart --version 0.1.0 --untar", ociSrv.RegistryURL), expectFile: "./oci-dependent-chart", expectDir: true, }, { name: "Fetch OCI Chart with untar and untardir", args: fmt.Sprintf("oci://%s/u/ocitestuser/oci-dependent-chart --version 0.1.0 --untar --untardir ocitest2", ociSrv.RegistryURL), expectFile: "./ocitest2", expectDir: true, }, { name: "OCI Fetch untar when dir with same name existed", args: fmt.Sprintf("oci://%s/u/ocitestuser/oci-dependent-chart --version 0.1.0 --untar --untardir ocitest2", ociSrv.RegistryURL), existDir: "ocitest2/oci-dependent-chart", wantError: true, wantErrorMsg: fmt.Sprintf("failed to untar: a file or directory with the name %s already exists", filepath.Join(srv.Root(), "ocitest2", "oci-dependent-chart")), }, { name: "Fail fetching non-existent OCI chart", args: fmt.Sprintf("oci://%s/u/ocitestuser/nosuchthing --version 0.1.0", ociSrv.RegistryURL), failExpect: "Failed to fetch", wantError: true, }, { name: "Fail fetching OCI chart without version specified", args: fmt.Sprintf("oci://%s/u/ocitestuser/nosuchthing", ociSrv.RegistryURL), wantError: true, }, { name: "Fetching OCI chart without version option specified", args: fmt.Sprintf("oci://%s/u/ocitestuser/oci-dependent-chart:0.1.0", ociSrv.RegistryURL), expectFile: "./oci-dependent-chart-0.1.0.tgz", }, { name: "Fetching OCI chart with version specified", args: fmt.Sprintf("oci://%s/u/ocitestuser/oci-dependent-chart:0.1.0 --version 0.1.0", ociSrv.RegistryURL), expectFile: "./oci-dependent-chart-0.1.0.tgz", }, { name: "Fail fetching OCI chart with version mismatch", args: fmt.Sprintf("oci://%s/u/ocitestuser/oci-dependent-chart:0.2.0 --version 0.1.0", ociSrv.RegistryURL), wantErrorMsg: "chart reference and version mismatch: 0.1.0 is not 0.2.0", wantError: true, }, } contentCache := t.TempDir() for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { outdir := srv.Root() cmd := fmt.Sprintf("fetch %s -d '%s' --repository-config %s --repository-cache %s --registry-config %s --content-cache %s --plain-http", tt.args, outdir, filepath.Join(outdir, "repositories.yaml"), outdir, filepath.Join(outdir, "config.json"), contentCache, ) // Create file or Dir before helm pull --untar, see: https://github.com/helm/helm/issues/7182 if tt.existFile != "" { file := filepath.Join(outdir, tt.existFile) if err := os.MkdirAll(filepath.Dir(file), 0755); err != nil { t.Fatal(err) } _, err := os.Create(file) if err != nil { t.Fatal(err) } } if tt.existDir != "" { file := filepath.Join(outdir, tt.existDir) err := os.MkdirAll(file, 0755) if err != nil { t.Fatal(err) } } _, out, err := executeActionCommand(cmd) if err != nil { if tt.wantError { if tt.wantErrorMsg != "" && tt.wantErrorMsg != err.Error() { t.Fatalf("Actual error '%s', not equal to expected error '%s'", err, tt.wantErrorMsg) } return } t.Fatalf("%q reported error: %s", tt.name, err) } if tt.expectVerify { outString := helmTestKeyOut + tt.expectSha + "\n" if out != outString { t.Errorf("%q: expected verification output %q, got %q", tt.name, outString, out) } } ef := filepath.Join(outdir, tt.expectFile) fi, err := os.Stat(ef) if err != nil { t.Errorf("%q: expected a file at %s. %s", tt.name, ef, err) } if fi.IsDir() != tt.expectDir { t.Errorf("%q: expected directory=%t, but it's not.", tt.name, tt.expectDir) } }) } } // runPullTests is a helper function to run pull command tests with common logic func runPullTests(t *testing.T, tests []struct { name string args string existFile string existDir string wantError bool wantErrorMsg string expectFile string expectDir bool }, outdir string, additionalFlags string) { t.Helper() for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { cmd := fmt.Sprintf("pull %s -d '%s' --repository-config %s --repository-cache %s --registry-config %s %s", tt.args, outdir, filepath.Join(outdir, "repositories.yaml"), outdir, filepath.Join(outdir, "config.json"), additionalFlags, ) // Create file or Dir before helm pull --untar, see: https://github.com/helm/helm/issues/7182 if tt.existFile != "" { file := filepath.Join(outdir, tt.existFile) _, err := os.Create(file) if err != nil { t.Fatal(err) } } if tt.existDir != "" { file := filepath.Join(outdir, tt.existDir) err := os.MkdirAll(file, 0755) if err != nil { t.Fatal(err) } } _, _, err := executeActionCommand(cmd) if tt.wantError && err == nil { t.Fatalf("%q: expected error but got none", tt.name) } if err != nil { if tt.wantError { if tt.wantErrorMsg != "" && tt.wantErrorMsg != err.Error() { t.Fatalf("Actual error '%s', not equal to expected error '%s'", err, tt.wantErrorMsg) } return } t.Fatalf("%q reported error: %s", tt.name, err) } ef := filepath.Join(outdir, tt.expectFile) fi, err := os.Stat(ef) if err != nil { t.Errorf("%q: expected a file at %s. %s", tt.name, ef, err) } if fi.IsDir() != tt.expectDir { t.Errorf("%q: expected directory=%t, but it's not.", tt.name, tt.expectDir) } }) } } // buildOCIURL is a helper function to build OCI URLs with credentials func buildOCIURL(registryURL, chartName, version, username, password string) string { baseURL := fmt.Sprintf("oci://%s/u/ocitestuser/%s", registryURL, chartName) if version != "" { baseURL += fmt.Sprintf(" --version %s", version) } if username != "" && password != "" { baseURL += fmt.Sprintf(" --username %s --password %s", username, password) } return baseURL } func TestPullWithCredentialsCmd(t *testing.T) { srv := repotest.NewTempServer( t, repotest.WithChartSourceGlob("testdata/testcharts/*.tgz*"), repotest.WithMiddleware(repotest.BasicAuthMiddleware(t)), ) defer srv.Stop() srv2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.FileServer(http.Dir(srv.Root())).ServeHTTP(w, r) })) defer srv2.Close() if err := srv.LinkIndices(); err != nil { t.Fatal(err) } // all flags will get "-d outdir" appended. tests := []struct { name string args string existFile string existDir string wantError bool wantErrorMsg string expectFile string expectDir bool }{ { name: "Chart fetch using repo URL", expectFile: "./signtest-0.1.0.tgz", args: "signtest --repo " + srv.URL() + " --username username --password password", }, { name: "Fail fetching non-existent chart on repo URL", args: "someChart --repo " + srv.URL() + " --username username --password password", wantError: true, }, { name: "Specific version chart fetch using repo URL", expectFile: "./signtest-0.1.0.tgz", args: "signtest --version=0.1.0 --repo " + srv.URL() + " --username username --password password", }, { name: "Specific version chart fetch using repo URL", args: "signtest --version=0.2.0 --repo " + srv.URL() + " --username username --password password", wantError: true, }, { name: "Chart located on different domain with credentials passed", args: "reqtest --repo " + srv2.URL + " --username username --password password --pass-credentials", expectFile: "./reqtest-0.1.0.tgz", }, } runPullTests(t, tests, srv.Root(), "") } func TestPullVersionCompletion(t *testing.T) { repoFile := "testdata/helmhome/helm/repositories.yaml" repoCache := "testdata/helmhome/helm/repository" repoSetup := fmt.Sprintf("--repository-config %s --repository-cache %s", repoFile, repoCache) tests := []cmdTestCase{{ name: "completion for pull version flag", cmd: fmt.Sprintf("%s __complete pull testing/alpine --version ''", repoSetup), golden: "output/version-comp.txt", }, { name: "completion for pull version flag, no filter", cmd: fmt.Sprintf("%s __complete pull testing/alpine --version 0.3", repoSetup), golden: "output/version-comp.txt", }, { name: "completion for pull version flag too few args", cmd: fmt.Sprintf("%s __complete pull --version ''", repoSetup), golden: "output/version-invalid-comp.txt", }, { name: "completion for pull version flag too many args", cmd: fmt.Sprintf("%s __complete pull testing/alpine badarg --version ''", repoSetup), golden: "output/version-invalid-comp.txt", }, { name: "completion for pull version flag invalid chart", cmd: fmt.Sprintf("%s __complete pull invalid/invalid --version ''", repoSetup), golden: "output/version-invalid-comp.txt", }} runTestCmd(t, tests) } func TestPullWithCredentialsCmdOCIRegistry(t *testing.T) { srv := repotest.NewTempServer( t, repotest.WithChartSourceGlob("testdata/testcharts/*.tgz*"), ) defer srv.Stop() ociSrv, err := repotest.NewOCIServer(t, srv.Root()) if err != nil { t.Fatal(err) } ociSrv.Run(t) if err := srv.LinkIndices(); err != nil { t.Fatal(err) } // all flags will get "-d outdir" appended. tests := []struct { name string args string existFile string existDir string wantError bool wantErrorMsg string expectFile string expectDir bool }{ { name: "OCI Chart fetch with credentials", args: buildOCIURL(ociSrv.RegistryURL, "oci-dependent-chart", "0.1.0", ociSrv.TestUsername, ociSrv.TestPassword), expectFile: "./oci-dependent-chart-0.1.0.tgz", }, { name: "OCI Chart fetch with credentials and untar", args: buildOCIURL(ociSrv.RegistryURL, "oci-dependent-chart", "0.1.0", ociSrv.TestUsername, ociSrv.TestPassword) + " --untar", expectFile: "./oci-dependent-chart", expectDir: true, }, { name: "OCI Chart fetch with credentials and untardir", args: buildOCIURL(ociSrv.RegistryURL, "oci-dependent-chart", "0.1.0", ociSrv.TestUsername, ociSrv.TestPassword) + " --untar --untardir ocitest-credentials", expectFile: "./ocitest-credentials", expectDir: true, }, { name: "Fail fetching OCI chart with wrong credentials", args: buildOCIURL(ociSrv.RegistryURL, "oci-dependent-chart", "0.1.0", "wronguser", "wrongpass"), wantError: true, }, { name: "Fail fetching non-existent OCI chart with credentials", args: buildOCIURL(ociSrv.RegistryURL, "nosuchthing", "0.1.0", ociSrv.TestUsername, ociSrv.TestPassword), wantError: true, }, { name: "Fail fetching OCI chart without version specified", args: buildOCIURL(ociSrv.RegistryURL, "nosuchthing", "", ociSrv.TestUsername, ociSrv.TestPassword), wantError: true, }, } runPullTests(t, tests, srv.Root(), "--plain-http") } func TestPullFileCompletion(t *testing.T) { checkFileCompletion(t, "pull", false) checkFileCompletion(t, "pull repo/chart", false) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/printer.go
pkg/cmd/printer.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "io" "text/template" ) func tpl(t string, vals map[string]interface{}, out io.Writer) error { tt, err := template.New("_").Parse(t) if err != nil { return err } return tt.Execute(out, vals) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/helpers_test.go
pkg/cmd/helpers_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "bytes" "encoding/json" "io" "log/slog" "os" "strings" "testing" "time" shellwords "github.com/mattn/go-shellwords" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "helm.sh/helm/v4/internal/test" "helm.sh/helm/v4/pkg/action" "helm.sh/helm/v4/pkg/chart/common" "helm.sh/helm/v4/pkg/cli" kubefake "helm.sh/helm/v4/pkg/kube/fake" release "helm.sh/helm/v4/pkg/release/v1" "helm.sh/helm/v4/pkg/storage" "helm.sh/helm/v4/pkg/storage/driver" ) func testTimestamper() time.Time { return time.Unix(242085845, 0).UTC() } func init() { action.Timestamper = testTimestamper } func runTestCmd(t *testing.T, tests []cmdTestCase) { t.Helper() for _, tt := range tests { for i := 0; i <= tt.repeat; i++ { t.Run(tt.name, func(t *testing.T) { defer resetEnv()() storage := storageFixture() for _, rel := range tt.rels { if err := storage.Create(rel); err != nil { t.Fatal(err) } } t.Logf("running cmd (attempt %d): %s", i+1, tt.cmd) _, out, err := executeActionCommandC(storage, tt.cmd) if tt.wantError && err == nil { t.Errorf("expected error, got success with the following output:\n%s", out) } if !tt.wantError && err != nil { t.Errorf("expected no error, got: '%v'", err) } if tt.golden != "" { test.AssertGoldenString(t, out, tt.golden) } }) } } } func storageFixture() *storage.Storage { return storage.Init(driver.NewMemory()) } func executeActionCommandC(store *storage.Storage, cmd string) (*cobra.Command, string, error) { return executeActionCommandStdinC(store, nil, cmd) } func executeActionCommandStdinC(store *storage.Storage, in *os.File, cmd string) (*cobra.Command, string, error) { args, err := shellwords.Parse(cmd) if err != nil { return nil, "", err } buf := new(bytes.Buffer) actionConfig := &action.Configuration{ Releases: store, KubeClient: &kubefake.PrintingKubeClient{Out: io.Discard}, Capabilities: common.DefaultCapabilities, } root, err := newRootCmdWithConfig(actionConfig, buf, args, SetupLogging) if err != nil { return nil, "", err } root.SetOut(buf) root.SetErr(buf) root.SetArgs(args) oldStdin := os.Stdin defer func() { os.Stdin = oldStdin }() if in != nil { root.SetIn(in) os.Stdin = in } if mem, ok := store.Driver.(*driver.Memory); ok { mem.SetNamespace(settings.Namespace()) } c, err := root.ExecuteC() result := buf.String() return c, result, err } // cmdTestCase describes a test case that works with releases. type cmdTestCase struct { name string cmd string golden string wantError bool // Rels are the available releases at the start of the test. rels []*release.Release // Number of repeats (in case a feature was previously flaky and the test checks // it's now stably producing identical results). 0 means test is run exactly once. repeat int } func executeActionCommand(cmd string) (*cobra.Command, string, error) { return executeActionCommandC(storageFixture(), cmd) } func resetEnv() func() { origEnv := os.Environ() return func() { os.Clearenv() for _, pair := range origEnv { kv := strings.SplitN(pair, "=", 2) os.Setenv(kv[0], kv[1]) } settings = cli.New() } } func TestCmdGetDryRunFlagStrategy(t *testing.T) { type testCaseExpectedLog struct { Level string Msg string } testCases := map[string]struct { DryRunFlagArg string IsTemplate bool ExpectedStrategy action.DryRunStrategy ExpectedError bool ExpectedLog *testCaseExpectedLog }{ "unset_value": { DryRunFlagArg: "--dry-run", ExpectedStrategy: action.DryRunClient, ExpectedLog: &testCaseExpectedLog{ Level: "WARN", Msg: `--dry-run is deprecated and should be replaced with '--dry-run=client'`, }, }, "unset_special": { DryRunFlagArg: "--dry-run=unset", // Special value that matches cmd.Flags("dry-run").NoOptDefVal ExpectedStrategy: action.DryRunClient, ExpectedLog: &testCaseExpectedLog{ Level: "WARN", Msg: `--dry-run is deprecated and should be replaced with '--dry-run=client'`, }, }, "none": { DryRunFlagArg: "--dry-run=none", ExpectedStrategy: action.DryRunNone, }, "client": { DryRunFlagArg: "--dry-run=client", ExpectedStrategy: action.DryRunClient, }, "server": { DryRunFlagArg: "--dry-run=server", ExpectedStrategy: action.DryRunServer, }, "bool_false": { DryRunFlagArg: "--dry-run=false", ExpectedStrategy: action.DryRunNone, ExpectedLog: &testCaseExpectedLog{ Level: "WARN", Msg: `boolean '--dry-run=false' flag is deprecated and must be replaced with '--dry-run=none'`, }, }, "bool_true": { DryRunFlagArg: "--dry-run=true", ExpectedStrategy: action.DryRunClient, ExpectedLog: &testCaseExpectedLog{ Level: "WARN", Msg: `boolean '--dry-run=true' flag is deprecated and must be replaced with '--dry-run=client'`, }, }, "bool_0": { DryRunFlagArg: "--dry-run=0", ExpectedStrategy: action.DryRunNone, ExpectedLog: &testCaseExpectedLog{ Level: "WARN", Msg: `boolean '--dry-run=0' flag is deprecated and must be replaced with '--dry-run=none'`, }, }, "bool_1": { DryRunFlagArg: "--dry-run=1", ExpectedStrategy: action.DryRunClient, ExpectedLog: &testCaseExpectedLog{ Level: "WARN", Msg: `boolean '--dry-run=1' flag is deprecated and must be replaced with '--dry-run=client'`, }, }, "invalid": { DryRunFlagArg: "--dry-run=invalid", ExpectedError: true, }, "template_unset_value": { DryRunFlagArg: "--dry-run", IsTemplate: true, ExpectedStrategy: action.DryRunClient, ExpectedLog: &testCaseExpectedLog{ Level: "WARN", Msg: `--dry-run is deprecated and should be replaced with '--dry-run=client'`, }, }, "template_bool_false": { DryRunFlagArg: "--dry-run=false", IsTemplate: true, ExpectedError: true, }, "template_bool_template_true": { DryRunFlagArg: "--dry-run=true", IsTemplate: true, ExpectedStrategy: action.DryRunClient, ExpectedLog: &testCaseExpectedLog{ Level: "WARN", Msg: `boolean '--dry-run=true' flag is deprecated and must be replaced with '--dry-run=client'`, }, }, "template_none": { DryRunFlagArg: "--dry-run=none", IsTemplate: true, ExpectedError: true, }, "template_client": { DryRunFlagArg: "--dry-run=client", IsTemplate: true, ExpectedStrategy: action.DryRunClient, }, "template_server": { DryRunFlagArg: "--dry-run=server", IsTemplate: true, ExpectedStrategy: action.DryRunServer, }, } for name, tc := range testCases { logBuf := new(bytes.Buffer) logger := slog.New(slog.NewJSONHandler(logBuf, nil)) slog.SetDefault(logger) cmd := &cobra.Command{ Use: "helm", } addDryRunFlag(cmd) cmd.Flags().Parse([]string{"helm", tc.DryRunFlagArg}) t.Run(name, func(t *testing.T) { dryRunStrategy, err := cmdGetDryRunFlagStrategy(cmd, tc.IsTemplate) if tc.ExpectedError { assert.Error(t, err) } else { assert.Nil(t, err) assert.Equal(t, tc.ExpectedStrategy, dryRunStrategy) } if tc.ExpectedLog != nil { logResult := map[string]string{} err = json.Unmarshal(logBuf.Bytes(), &logResult) require.Nil(t, err) assert.Equal(t, tc.ExpectedLog.Level, logResult["level"]) assert.Equal(t, tc.ExpectedLog.Msg, logResult["msg"]) } else { assert.Equal(t, 0, logBuf.Len()) } }) } }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/get_all_test.go
pkg/cmd/get_all_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "testing" release "helm.sh/helm/v4/pkg/release/v1" ) func TestGetCmd(t *testing.T) { tests := []cmdTestCase{{ name: "get all with a release", cmd: "get all thomas-guide", golden: "output/get-release.txt", rels: []*release.Release{release.Mock(&release.MockReleaseOptions{Name: "thomas-guide"})}, }, { name: "get all with a formatted release", cmd: "get all elevated-turkey --template {{.Release.Chart.Metadata.Version}}", golden: "output/get-release-template.txt", rels: []*release.Release{release.Mock(&release.MockReleaseOptions{Name: "elevated-turkey"})}, }, { name: "get all requires release name arg", cmd: "get all", golden: "output/get-all-no-args.txt", wantError: true, }} runTestCmd(t, tests) } func TestGetAllCompletion(t *testing.T) { checkReleaseCompletion(t, "get all", false) } func TestGetAllRevisionCompletion(t *testing.T) { revisionFlagCompletionTest(t, "get all") } func TestGetAllFileCompletion(t *testing.T) { checkFileCompletion(t, "get all", false) checkFileCompletion(t, "get all myrelease", false) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/verify_test.go
pkg/cmd/verify_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "runtime" "testing" ) func TestVerifyCmd(t *testing.T) { statExe := "stat" statPathMsg := "no such file or directory" statFileMsg := statPathMsg if runtime.GOOS == "windows" { statExe = "FindFirstFile" statPathMsg = "The system cannot find the path specified." statFileMsg = "The system cannot find the file specified." } tests := []struct { name string cmd string expect string wantError bool }{ { name: "verify requires a chart", cmd: "verify", expect: "\"helm verify\" requires 1 argument\n\nUsage: helm verify PATH [flags]", wantError: true, }, { name: "verify requires that chart exists", cmd: "verify no/such/file", expect: fmt.Sprintf("%s no/such/file: %s", statExe, statPathMsg), wantError: true, }, { name: "verify requires that chart is not a directory", cmd: "verify testdata/testcharts/signtest", expect: "unpacked charts cannot be verified", wantError: true, }, { name: "verify requires that chart has prov file", cmd: "verify testdata/testcharts/compressedchart-0.1.0.tgz", expect: fmt.Sprintf("could not load provenance file testdata/testcharts/compressedchart-0.1.0.tgz.prov: %s testdata/testcharts/compressedchart-0.1.0.tgz.prov: %s", statExe, statFileMsg), wantError: true, }, { name: "verify validates a properly signed chart", cmd: "verify testdata/testcharts/signtest-0.1.0.tgz --keyring testdata/helm-test-key.pub", expect: "Signed by: Helm Testing (This key should only be used for testing. DO NOT TRUST.) <helm-testing@helm.sh>\nUsing Key With Fingerprint: 5E615389B53CA37F0EE60BD3843BBF981FC18762\nChart Hash Verified: sha256:e5ef611620fb97704d8751c16bab17fedb68883bfb0edc76f78a70e9173f9b55\n", wantError: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { _, out, err := executeActionCommand(tt.cmd) if tt.wantError { if err == nil { t.Errorf("Expected error, but got none: %q", out) } if err.Error() != tt.expect { t.Errorf("Expected error %q, got %q", tt.expect, err) } return } else if err != nil { t.Errorf("Unexpected error: %s", err) } if out != tt.expect { t.Errorf("Expected %q, got %q", tt.expect, out) } }) } } func TestVerifyFileCompletion(t *testing.T) { checkFileCompletion(t, "verify", true) checkFileCompletion(t, "verify mypath", false) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/uninstall.go
pkg/cmd/uninstall.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "io" "time" "github.com/spf13/cobra" "helm.sh/helm/v4/pkg/action" "helm.sh/helm/v4/pkg/cmd/require" ) const uninstallDesc = ` This command takes a release name and uninstalls the release. It removes all of the resources associated with the last release of the chart as well as the release history, freeing it up for future use. Use the '--dry-run' flag to see which releases will be uninstalled without actually uninstalling them. ` func newUninstallCmd(cfg *action.Configuration, out io.Writer) *cobra.Command { client := action.NewUninstall(cfg) cmd := &cobra.Command{ Use: "uninstall RELEASE_NAME [...]", Aliases: []string{"del", "delete", "un"}, SuggestFor: []string{"remove", "rm"}, Short: "uninstall a release", Long: uninstallDesc, Args: require.MinimumNArgs(1), ValidArgsFunction: func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return compListReleases(toComplete, args, cfg) }, RunE: func(_ *cobra.Command, args []string) error { validationErr := validateCascadeFlag(client) if validationErr != nil { return validationErr } for i := range args { res, err := client.Run(args[i]) if err != nil { return err } if res != nil && res.Info != "" { fmt.Fprintln(out, res.Info) } fmt.Fprintf(out, "release \"%s\" uninstalled\n", args[i]) } return nil }, } f := cmd.Flags() f.BoolVar(&client.DryRun, "dry-run", false, "simulate a uninstall") f.BoolVar(&client.DisableHooks, "no-hooks", false, "prevent hooks from running during uninstallation") f.BoolVar(&client.IgnoreNotFound, "ignore-not-found", false, `Treat "release not found" as a successful uninstall`) f.BoolVar(&client.KeepHistory, "keep-history", false, "remove all associated resources and mark the release as deleted, but retain the release history") f.StringVar(&client.DeletionPropagation, "cascade", "background", "Must be \"background\", \"orphan\", or \"foreground\". Selects the deletion cascading strategy for the dependents. Defaults to background.") f.DurationVar(&client.Timeout, "timeout", 300*time.Second, "time to wait for any individual Kubernetes operation (like Jobs for hooks)") f.StringVar(&client.Description, "description", "", "add a custom description") AddWaitFlag(cmd, &client.WaitStrategy) return cmd } func validateCascadeFlag(client *action.Uninstall) error { if client.DeletionPropagation != "background" && client.DeletionPropagation != "foreground" && client.DeletionPropagation != "orphan" { return fmt.Errorf("invalid cascade value (%s). Must be \"background\", \"foreground\", or \"orphan\"", client.DeletionPropagation) } return nil }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/upgrade_test.go
pkg/cmd/upgrade_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "os" "path/filepath" "reflect" "strings" "testing" "time" "helm.sh/helm/v4/pkg/chart/common" chart "helm.sh/helm/v4/pkg/chart/v2" "helm.sh/helm/v4/pkg/chart/v2/loader" chartutil "helm.sh/helm/v4/pkg/chart/v2/util" rcommon "helm.sh/helm/v4/pkg/release/common" release "helm.sh/helm/v4/pkg/release/v1" ) func TestUpgradeCmd(t *testing.T) { tmpChart := t.TempDir() cfile := &chart.Chart{ Metadata: &chart.Metadata{ APIVersion: chart.APIVersionV1, Name: "testUpgradeChart", Description: "A Helm chart for Kubernetes", Version: "0.1.0", }, } chartPath := filepath.Join(tmpChart, cfile.Metadata.Name) if err := chartutil.SaveDir(cfile, tmpChart); err != nil { t.Fatalf("Error creating chart for upgrade: %v", err) } ch, err := loader.Load(chartPath) if err != nil { t.Fatalf("Error loading chart: %v", err) } _ = release.Mock(&release.MockReleaseOptions{ Name: "funny-bunny", Chart: ch, }) // update chart version cfile.Metadata.Version = "0.1.2" if err := chartutil.SaveDir(cfile, tmpChart); err != nil { t.Fatalf("Error creating chart: %v", err) } ch, err = loader.Load(chartPath) if err != nil { t.Fatalf("Error loading updated chart: %v", err) } // update chart version again cfile.Metadata.Version = "0.1.3" if err := chartutil.SaveDir(cfile, tmpChart); err != nil { t.Fatalf("Error creating chart: %v", err) } var ch2 *chart.Chart ch2, err = loader.Load(chartPath) if err != nil { t.Fatalf("Error loading updated chart: %v", err) } missingDepsPath := "testdata/testcharts/chart-missing-deps" badDepsPath := "testdata/testcharts/chart-bad-requirements" presentDepsPath := "testdata/testcharts/chart-with-subchart-update" relWithStatusMock := func(n string, v int, ch *chart.Chart, status rcommon.Status) *release.Release { return release.Mock(&release.MockReleaseOptions{Name: n, Version: v, Chart: ch, Status: status}) } relMock := func(n string, v int, ch *chart.Chart) *release.Release { return release.Mock(&release.MockReleaseOptions{Name: n, Version: v, Chart: ch}) } tests := []cmdTestCase{ { name: "upgrade a release", cmd: fmt.Sprintf("upgrade funny-bunny '%s'", chartPath), golden: "output/upgrade.txt", rels: []*release.Release{relMock("funny-bunny", 2, ch)}, }, { name: "upgrade a release with timeout", cmd: fmt.Sprintf("upgrade funny-bunny --timeout 120s '%s'", chartPath), golden: "output/upgrade-with-timeout.txt", rels: []*release.Release{relMock("funny-bunny", 3, ch2)}, }, { name: "upgrade a release with --reset-values", cmd: fmt.Sprintf("upgrade funny-bunny --reset-values '%s'", chartPath), golden: "output/upgrade-with-reset-values.txt", rels: []*release.Release{relMock("funny-bunny", 4, ch2)}, }, { name: "upgrade a release with --reuse-values", cmd: fmt.Sprintf("upgrade funny-bunny --reuse-values '%s'", chartPath), golden: "output/upgrade-with-reset-values2.txt", rels: []*release.Release{relMock("funny-bunny", 5, ch2)}, }, { name: "upgrade a release with --take-ownership", cmd: fmt.Sprintf("upgrade funny-bunny '%s' --take-ownership", chartPath), golden: "output/upgrade-and-take-ownership.txt", rels: []*release.Release{relMock("funny-bunny", 2, ch)}, }, { name: "install a release with 'upgrade --install'", cmd: fmt.Sprintf("upgrade zany-bunny -i '%s'", chartPath), golden: "output/upgrade-with-install.txt", rels: []*release.Release{relMock("zany-bunny", 1, ch)}, }, { name: "install a release with 'upgrade --install' and timeout", cmd: fmt.Sprintf("upgrade crazy-bunny -i --timeout 120s '%s'", chartPath), golden: "output/upgrade-with-install-timeout.txt", rels: []*release.Release{relMock("crazy-bunny", 1, ch)}, }, { name: "upgrade a release with wait", cmd: fmt.Sprintf("upgrade crazy-bunny --wait '%s'", chartPath), golden: "output/upgrade-with-wait.txt", rels: []*release.Release{relMock("crazy-bunny", 2, ch2)}, }, { name: "upgrade a release with wait-for-jobs", cmd: fmt.Sprintf("upgrade crazy-bunny --wait --wait-for-jobs '%s'", chartPath), golden: "output/upgrade-with-wait-for-jobs.txt", rels: []*release.Release{relMock("crazy-bunny", 2, ch2)}, }, { name: "upgrade a release with missing dependencies", cmd: fmt.Sprintf("upgrade bonkers-bunny %s", missingDepsPath), golden: "output/upgrade-with-missing-dependencies.txt", wantError: true, }, { name: "upgrade a release with bad dependencies", cmd: fmt.Sprintf("upgrade bonkers-bunny '%s'", badDepsPath), golden: "output/upgrade-with-bad-dependencies.txt", wantError: true, }, { name: "upgrade a release with resolving missing dependencies", cmd: fmt.Sprintf("upgrade --dependency-update funny-bunny %s", presentDepsPath), golden: "output/upgrade-with-dependency-update.txt", rels: []*release.Release{relMock("funny-bunny", 2, ch2)}, }, { name: "upgrade a non-existent release", cmd: fmt.Sprintf("upgrade funny-bunny '%s'", chartPath), golden: "output/upgrade-with-bad-or-missing-existing-release.txt", wantError: true, }, { name: "upgrade a failed release", cmd: fmt.Sprintf("upgrade funny-bunny '%s'", chartPath), golden: "output/upgrade.txt", rels: []*release.Release{relWithStatusMock("funny-bunny", 2, ch, rcommon.StatusFailed)}, }, { name: "upgrade a pending install release", cmd: fmt.Sprintf("upgrade funny-bunny '%s'", chartPath), golden: "output/upgrade-with-pending-install.txt", wantError: true, rels: []*release.Release{relWithStatusMock("funny-bunny", 2, ch, rcommon.StatusPendingInstall)}, }, { name: "install a previously uninstalled release with '--keep-history' using 'upgrade --install'", cmd: fmt.Sprintf("upgrade funny-bunny -i '%s'", chartPath), golden: "output/upgrade-uninstalled-with-keep-history.txt", rels: []*release.Release{relWithStatusMock("funny-bunny", 2, ch, rcommon.StatusUninstalled)}, }, } runTestCmd(t, tests) } func TestUpgradeWithValue(t *testing.T) { releaseName := "funny-bunny-v2" relMock, ch, chartPath := prepareMockRelease(t, releaseName) defer resetEnv()() store := storageFixture() store.Create(relMock(releaseName, 3, ch)) cmd := fmt.Sprintf("upgrade %s --set favoriteDrink=tea '%s'", releaseName, chartPath) _, _, err := executeActionCommandC(store, cmd) if err != nil { t.Errorf("unexpected error, got '%v'", err) } updatedReli, err := store.Get(releaseName, 4) if err != nil { t.Errorf("unexpected error, got '%v'", err) } updatedRel, err := releaserToV1Release(updatedReli) if err != nil { t.Errorf("unexpected error, got '%v'", err) } if !strings.Contains(updatedRel.Manifest, "drink: tea") { t.Errorf("The value is not set correctly. manifest: %s", updatedRel.Manifest) } } func TestUpgradeWithStringValue(t *testing.T) { releaseName := "funny-bunny-v3" relMock, ch, chartPath := prepareMockRelease(t, releaseName) defer resetEnv()() store := storageFixture() store.Create(relMock(releaseName, 3, ch)) cmd := fmt.Sprintf("upgrade %s --set-string favoriteDrink=coffee '%s'", releaseName, chartPath) _, _, err := executeActionCommandC(store, cmd) if err != nil { t.Errorf("unexpected error, got '%v'", err) } updatedReli, err := store.Get(releaseName, 4) if err != nil { t.Errorf("unexpected error, got '%v'", err) } updatedRel, err := releaserToV1Release(updatedReli) if err != nil { t.Errorf("unexpected error, got '%v'", err) } if !strings.Contains(updatedRel.Manifest, "drink: coffee") { t.Errorf("The value is not set correctly. manifest: %s", updatedRel.Manifest) } } func TestUpgradeInstallWithSubchartNotes(t *testing.T) { releaseName := "wacky-bunny-v1" relMock, ch, _ := prepareMockRelease(t, releaseName) defer resetEnv()() store := storageFixture() store.Create(relMock(releaseName, 1, ch)) cmd := fmt.Sprintf("upgrade %s -i --render-subchart-notes '%s'", releaseName, "testdata/testcharts/chart-with-subchart-notes") _, _, err := executeActionCommandC(store, cmd) if err != nil { t.Errorf("unexpected error, got '%v'", err) } upgradedReli, err := store.Get(releaseName, 2) if err != nil { t.Errorf("unexpected error, got '%v'", err) } upgradedRel, err := releaserToV1Release(upgradedReli) if err != nil { t.Errorf("unexpected error, got '%v'", err) } if !strings.Contains(upgradedRel.Info.Notes, "PARENT NOTES") { t.Errorf("The parent notes are not set correctly. NOTES: %s", upgradedRel.Info.Notes) } if !strings.Contains(upgradedRel.Info.Notes, "SUBCHART NOTES") { t.Errorf("The subchart notes are not set correctly. NOTES: %s", upgradedRel.Info.Notes) } } func TestUpgradeWithValuesFile(t *testing.T) { releaseName := "funny-bunny-v4" relMock, ch, chartPath := prepareMockRelease(t, releaseName) defer resetEnv()() store := storageFixture() store.Create(relMock(releaseName, 3, ch)) cmd := fmt.Sprintf("upgrade %s --values testdata/testcharts/upgradetest/values.yaml '%s'", releaseName, chartPath) _, _, err := executeActionCommandC(store, cmd) if err != nil { t.Errorf("unexpected error, got '%v'", err) } updatedReli, err := store.Get(releaseName, 4) if err != nil { t.Errorf("unexpected error, got '%v'", err) } updatedRel, err := releaserToV1Release(updatedReli) if err != nil { t.Errorf("unexpected error, got '%v'", err) } if !strings.Contains(updatedRel.Manifest, "drink: beer") { t.Errorf("The value is not set correctly. manifest: %s", updatedRel.Manifest) } } func TestUpgradeWithValuesFromStdin(t *testing.T) { releaseName := "funny-bunny-v5" relMock, ch, chartPath := prepareMockRelease(t, releaseName) defer resetEnv()() store := storageFixture() store.Create(relMock(releaseName, 3, ch)) in, err := os.Open("testdata/testcharts/upgradetest/values.yaml") if err != nil { t.Errorf("unexpected error, got '%v'", err) } cmd := fmt.Sprintf("upgrade %s --values - '%s'", releaseName, chartPath) _, _, err = executeActionCommandStdinC(store, in, cmd) if err != nil { t.Errorf("unexpected error, got '%v'", err) } updatedReli, err := store.Get(releaseName, 4) if err != nil { t.Errorf("unexpected error, got '%v'", err) } updatedRel, err := releaserToV1Release(updatedReli) if err != nil { t.Errorf("unexpected error, got '%v'", err) } if !strings.Contains(updatedRel.Manifest, "drink: beer") { t.Errorf("The value is not set correctly. manifest: %s", updatedRel.Manifest) } } func TestUpgradeInstallWithValuesFromStdin(t *testing.T) { releaseName := "funny-bunny-v6" _, _, chartPath := prepareMockRelease(t, releaseName) defer resetEnv()() store := storageFixture() in, err := os.Open("testdata/testcharts/upgradetest/values.yaml") if err != nil { t.Errorf("unexpected error, got '%v'", err) } cmd := fmt.Sprintf("upgrade %s -f - --install '%s'", releaseName, chartPath) _, _, err = executeActionCommandStdinC(store, in, cmd) if err != nil { t.Errorf("unexpected error, got '%v'", err) } updatedReli, err := store.Get(releaseName, 1) if err != nil { t.Errorf("unexpected error, got '%v'", err) } updatedRel, err := releaserToV1Release(updatedReli) if err != nil { t.Errorf("unexpected error, got '%v'", err) } if !strings.Contains(updatedRel.Manifest, "drink: beer") { t.Errorf("The value is not set correctly. manifest: %s", updatedRel.Manifest) } } func prepareMockRelease(t *testing.T, releaseName string) (func(n string, v int, ch *chart.Chart) *release.Release, *chart.Chart, string) { t.Helper() tmpChart := t.TempDir() configmapData, err := os.ReadFile("testdata/testcharts/upgradetest/templates/configmap.yaml") if err != nil { t.Fatalf("Error loading template yaml %v", err) } cfile := &chart.Chart{ Metadata: &chart.Metadata{ APIVersion: chart.APIVersionV1, Name: "testUpgradeChart", Description: "A Helm chart for Kubernetes", Version: "0.1.0", }, Templates: []*common.File{{Name: "templates/configmap.yaml", ModTime: time.Now(), Data: configmapData}}, } chartPath := filepath.Join(tmpChart, cfile.Metadata.Name) if err := chartutil.SaveDir(cfile, tmpChart); err != nil { t.Fatalf("Error creating chart for upgrade: %v", err) } ch, err := loader.Load(chartPath) if err != nil { t.Fatalf("Error loading chart: %v", err) } _ = release.Mock(&release.MockReleaseOptions{ Name: releaseName, Chart: ch, }) relMock := func(n string, v int, ch *chart.Chart) *release.Release { return release.Mock(&release.MockReleaseOptions{Name: n, Version: v, Chart: ch}) } return relMock, ch, chartPath } func TestUpgradeOutputCompletion(t *testing.T) { outputFlagCompletionTest(t, "upgrade") } func TestUpgradeVersionCompletion(t *testing.T) { repoFile := "testdata/helmhome/helm/repositories.yaml" repoCache := "testdata/helmhome/helm/repository" repoSetup := fmt.Sprintf("--repository-config %s --repository-cache %s", repoFile, repoCache) tests := []cmdTestCase{{ name: "completion for upgrade version flag", cmd: fmt.Sprintf("%s __complete upgrade releasename testing/alpine --version ''", repoSetup), golden: "output/version-comp.txt", }, { name: "completion for upgrade version flag, no filter", cmd: fmt.Sprintf("%s __complete upgrade releasename testing/alpine --version 0.3", repoSetup), golden: "output/version-comp.txt", }, { name: "completion for upgrade version flag too few args", cmd: fmt.Sprintf("%s __complete upgrade releasename --version ''", repoSetup), golden: "output/version-invalid-comp.txt", }, { name: "completion for upgrade version flag too many args", cmd: fmt.Sprintf("%s __complete upgrade releasename testing/alpine badarg --version ''", repoSetup), golden: "output/version-invalid-comp.txt", }, { name: "completion for upgrade version flag invalid chart", cmd: fmt.Sprintf("%s __complete upgrade releasename invalid/invalid --version ''", repoSetup), golden: "output/version-invalid-comp.txt", }} runTestCmd(t, tests) } func TestUpgradeFileCompletion(t *testing.T) { checkFileCompletion(t, "upgrade", false) checkFileCompletion(t, "upgrade myrelease", true) checkFileCompletion(t, "upgrade myrelease repo/chart", false) } func TestUpgradeInstallWithLabels(t *testing.T) { releaseName := "funny-bunny-labels" _, _, chartPath := prepareMockRelease(t, releaseName) defer resetEnv()() store := storageFixture() expectedLabels := map[string]string{ "key1": "val1", "key2": "val2", } cmd := fmt.Sprintf("upgrade %s --install --labels key1=val1,key2=val2 '%s'", releaseName, chartPath) _, _, err := executeActionCommandC(store, cmd) if err != nil { t.Errorf("unexpected error, got '%v'", err) } updatedReli, err := store.Get(releaseName, 1) if err != nil { t.Errorf("unexpected error, got '%v'", err) } updatedRel, err := releaserToV1Release(updatedReli) if err != nil { t.Errorf("unexpected error, got '%v'", err) } if !reflect.DeepEqual(updatedRel.Labels, expectedLabels) { t.Errorf("Expected {%v}, got {%v}", expectedLabels, updatedRel.Labels) } } func prepareMockReleaseWithSecret(t *testing.T, releaseName string) (func(n string, v int, ch *chart.Chart) *release.Release, *chart.Chart, string) { t.Helper() tmpChart := t.TempDir() configmapData, err := os.ReadFile("testdata/testcharts/chart-with-secret/templates/configmap.yaml") if err != nil { t.Fatalf("Error loading template yaml %v", err) } secretData, err := os.ReadFile("testdata/testcharts/chart-with-secret/templates/secret.yaml") if err != nil { t.Fatalf("Error loading template yaml %v", err) } modTime := time.Now() cfile := &chart.Chart{ Metadata: &chart.Metadata{ APIVersion: chart.APIVersionV1, Name: "testUpgradeChart", Description: "A Helm chart for Kubernetes", Version: "0.1.0", }, Templates: []*common.File{{Name: "templates/configmap.yaml", ModTime: modTime, Data: configmapData}, {Name: "templates/secret.yaml", ModTime: modTime, Data: secretData}}, } chartPath := filepath.Join(tmpChart, cfile.Metadata.Name) if err := chartutil.SaveDir(cfile, tmpChart); err != nil { t.Fatalf("Error creating chart for upgrade: %v", err) } ch, err := loader.Load(chartPath) if err != nil { t.Fatalf("Error loading chart: %v", err) } _ = release.Mock(&release.MockReleaseOptions{ Name: releaseName, Chart: ch, }) relMock := func(n string, v int, ch *chart.Chart) *release.Release { return release.Mock(&release.MockReleaseOptions{Name: n, Version: v, Chart: ch}) } return relMock, ch, chartPath } func TestUpgradeWithDryRun(t *testing.T) { releaseName := "funny-bunny-labels" _, _, chartPath := prepareMockReleaseWithSecret(t, releaseName) defer resetEnv()() store := storageFixture() // First install a release into the store so that future --dry-run attempts // have it available. cmd := fmt.Sprintf("upgrade %s --install '%s'", releaseName, chartPath) _, _, err := executeActionCommandC(store, cmd) if err != nil { t.Errorf("unexpected error, got '%v'", err) } _, err = store.Get(releaseName, 1) if err != nil { t.Errorf("unexpected error, got '%v'", err) } cmd = fmt.Sprintf("upgrade %s --dry-run '%s'", releaseName, chartPath) _, out, err := executeActionCommandC(store, cmd) if err != nil { t.Errorf("unexpected error, got '%v'", err) } // No second release should be stored because this is a dry run. _, err = store.Get(releaseName, 2) if err == nil { t.Error("expected error as there should be no new release but got none") } if !strings.Contains(out, "kind: Secret") { t.Error("expected secret in output from --dry-run but found none") } // Ensure the secret is not in the output cmd = fmt.Sprintf("upgrade %s --dry-run --hide-secret '%s'", releaseName, chartPath) _, out, err = executeActionCommandC(store, cmd) if err != nil { t.Errorf("unexpected error, got '%v'", err) } // No second release should be stored because this is a dry run. _, err = store.Get(releaseName, 2) if err == nil { t.Error("expected error as there should be no new release but got none") } if strings.Contains(out, "kind: Secret") { t.Error("expected no secret in output from --dry-run --hide-secret but found one") } // Ensure there is an error when --hide-secret used without dry-run cmd = fmt.Sprintf("upgrade %s --hide-secret '%s'", releaseName, chartPath) _, _, err = executeActionCommandC(store, cmd) if err == nil { t.Error("expected error when --hide-secret used without --dry-run") } } func TestUpgradeInstallServerSideApply(t *testing.T) { _, _, chartPath := prepareMockRelease(t, "ssa-test") defer resetEnv()() tests := []struct { name string serverSideFlag string expectedApplyMethod string }{ { name: "upgrade --install with --server-side=false uses client-side apply", serverSideFlag: "--server-side=false", expectedApplyMethod: "csa", }, { name: "upgrade --install with --server-side=true uses server-side apply", serverSideFlag: "--server-side=true", expectedApplyMethod: "ssa", }, { name: "upgrade --install with --server-side=auto uses server-side apply (default for new install)", serverSideFlag: "--server-side=auto", expectedApplyMethod: "ssa", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { store := storageFixture() releaseName := fmt.Sprintf("ssa-test-%s", tt.expectedApplyMethod) cmd := fmt.Sprintf("upgrade %s --install %s '%s'", releaseName, tt.serverSideFlag, chartPath) _, _, err := executeActionCommandC(store, cmd) if err != nil { t.Fatalf("unexpected error: %v", err) } rel, err := store.Get(releaseName, 1) if err != nil { t.Fatalf("unexpected error getting release: %v", err) } relV1, err := releaserToV1Release(rel) if err != nil { t.Fatalf("unexpected error converting release: %v", err) } if relV1.ApplyMethod != tt.expectedApplyMethod { t.Errorf("expected ApplyMethod %q, got %q", tt.expectedApplyMethod, relV1.ApplyMethod) } }) } }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/completion_test.go
pkg/cmd/completion_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "strings" "testing" chart "helm.sh/helm/v4/pkg/chart/v2" "helm.sh/helm/v4/pkg/release/common" release "helm.sh/helm/v4/pkg/release/v1" ) // Check if file completion should be performed according to parameter 'shouldBePerformed' func checkFileCompletion(t *testing.T, cmdName string, shouldBePerformed bool) { t.Helper() storage := storageFixture() storage.Create(&release.Release{ Name: "myrelease", Info: &release.Info{Status: common.StatusDeployed}, Chart: &chart.Chart{ Metadata: &chart.Metadata{ Name: "Myrelease-Chart", Version: "1.2.3", }, }, Version: 1, }) testcmd := fmt.Sprintf("__complete %s ''", cmdName) _, out, err := executeActionCommandC(storage, testcmd) if err != nil { t.Errorf("unexpected error, %s", err) } if !strings.Contains(out, "ShellCompDirectiveNoFileComp") != shouldBePerformed { if shouldBePerformed { t.Errorf("Unexpected directive ShellCompDirectiveNoFileComp when completing '%s'", cmdName) } else { t.Errorf("Did not receive directive ShellCompDirectiveNoFileComp when completing '%s'", cmdName) } t.Log(out) } } func TestCompletionFileCompletion(t *testing.T) { checkFileCompletion(t, "completion", false) checkFileCompletion(t, "completion bash", false) checkFileCompletion(t, "completion zsh", false) checkFileCompletion(t, "completion fish", false) } func checkReleaseCompletion(t *testing.T, cmdName string, multiReleasesAllowed bool) { t.Helper() multiReleaseTestGolden := "output/empty_nofile_comp.txt" if multiReleasesAllowed { multiReleaseTestGolden = "output/release_list_repeat_comp.txt" } tests := []cmdTestCase{{ name: "completion for uninstall", cmd: fmt.Sprintf("__complete %s ''", cmdName), golden: "output/release_list_comp.txt", rels: []*release.Release{ release.Mock(&release.MockReleaseOptions{Name: "athos"}), release.Mock(&release.MockReleaseOptions{Name: "porthos"}), release.Mock(&release.MockReleaseOptions{Name: "aramis"}), }, }, { name: "completion for uninstall repetition", cmd: fmt.Sprintf("__complete %s porthos ''", cmdName), golden: multiReleaseTestGolden, rels: []*release.Release{ release.Mock(&release.MockReleaseOptions{Name: "athos"}), release.Mock(&release.MockReleaseOptions{Name: "porthos"}), release.Mock(&release.MockReleaseOptions{Name: "aramis"}), }, }} for _, test := range tests { runTestCmd(t, []cmdTestCase{test}) } }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/install_test.go
pkg/cmd/install_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "net/http" "net/http/httptest" "path/filepath" "testing" "helm.sh/helm/v4/pkg/repo/v1/repotest" ) func TestInstall(t *testing.T) { srv := repotest.NewTempServer( t, repotest.WithChartSourceGlob("testdata/testcharts/*.tgz*"), repotest.WithMiddleware(repotest.BasicAuthMiddleware(t)), ) defer srv.Stop() srv2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.FileServer(http.Dir(srv.Root())).ServeHTTP(w, r) })) defer srv2.Close() if err := srv.LinkIndices(); err != nil { t.Fatal(err) } repoFile := filepath.Join(srv.Root(), "repositories.yaml") tests := []cmdTestCase{ // Install, base case { name: "basic install", cmd: "install aeneas testdata/testcharts/empty --namespace default", golden: "output/install.txt", }, // Install, values from cli { name: "install with values", cmd: "install virgil testdata/testcharts/alpine --set test.Name=bar", golden: "output/install-with-values.txt", }, // Install, values from cli via multiple --set { name: "install with multiple values", cmd: "install virgil testdata/testcharts/alpine --set test.Color=yellow --set test.Name=banana", golden: "output/install-with-multiple-values.txt", }, // Install, values from yaml { name: "install with values file", cmd: "install virgil testdata/testcharts/alpine -f testdata/testcharts/alpine/extra_values.yaml", golden: "output/install-with-values-file.txt", }, // Install, no hooks { name: "install without hooks", cmd: "install aeneas testdata/testcharts/alpine --no-hooks --set test.Name=hello", golden: "output/install-no-hooks.txt", }, // Install, values from multiple yaml { name: "install with values", cmd: "install virgil testdata/testcharts/alpine -f testdata/testcharts/alpine/extra_values.yaml -f testdata/testcharts/alpine/more_values.yaml", golden: "output/install-with-multiple-values-files.txt", }, // Install, no charts { name: "install with no chart specified", cmd: "install", golden: "output/install-no-args.txt", wantError: true, }, // Install, reuse name { name: "install and replace release", cmd: "install aeneas testdata/testcharts/empty --replace", golden: "output/install-and-replace.txt", }, // Install, take ownership { name: "install and replace release", cmd: "install aeneas-take-ownership testdata/testcharts/empty --take-ownership", golden: "output/install-and-take-ownership.txt", }, // Install, with timeout { name: "install with a timeout", cmd: "install foobar testdata/testcharts/empty --timeout 120s", golden: "output/install-with-timeout.txt", }, // Install, with wait { name: "install with a wait", cmd: "install apollo testdata/testcharts/empty --wait", golden: "output/install-with-wait.txt", }, // Install, with wait-for-jobs { name: "install with wait-for-jobs", cmd: "install apollo testdata/testcharts/empty --wait --wait-for-jobs", golden: "output/install-with-wait-for-jobs.txt", }, // Install, using the name-template { name: "install with name-template", cmd: "install testdata/testcharts/empty --name-template '{{ \"foobar\"}}'", golden: "output/install-name-template.txt", }, // Install, perform chart verification along the way. { name: "install with verification, missing provenance", cmd: "install bogus testdata/testcharts/compressedchart-0.1.0.tgz --verify --keyring testdata/helm-test-key.pub", wantError: true, }, { name: "install with verification, directory instead of file", cmd: "install bogus testdata/testcharts/signtest --verify --keyring testdata/helm-test-key.pub", wantError: true, }, { name: "install with verification, valid", cmd: "install signtest testdata/testcharts/signtest-0.1.0.tgz --verify --keyring testdata/helm-test-key.pub", }, // Install, chart with missing dependencies in /charts { name: "install chart with missing dependencies", cmd: "install nodeps testdata/testcharts/chart-missing-deps", wantError: true, }, // Install chart with update-dependency { name: "install chart with missing dependencies", cmd: "install --dependency-update updeps testdata/testcharts/chart-with-subchart-update", golden: "output/chart-with-subchart-update.txt", }, // Install, chart with bad dependencies in Chart.yaml in /charts { name: "install chart with bad dependencies in Chart.yaml", cmd: "install badreq testdata/testcharts/chart-bad-requirements", wantError: true, }, // Install, chart with library chart dependency { name: "install chart with library chart dependency", cmd: "install withlibchartp testdata/testcharts/chart-with-lib-dep", }, // Install, library chart { name: "install library chart", cmd: "install libchart testdata/testcharts/lib-chart", wantError: true, golden: "output/install-lib-chart.txt", }, // Install, chart with bad type { name: "install chart with bad type", cmd: "install badtype testdata/testcharts/chart-bad-type", wantError: true, golden: "output/install-chart-bad-type.txt", }, // Install, values from yaml, schematized { name: "install with schema file", cmd: "install schema testdata/testcharts/chart-with-schema", golden: "output/schema.txt", }, // Install, values from yaml, schematized with errors { name: "install with schema file, with errors", cmd: "install schema testdata/testcharts/chart-with-schema-negative", wantError: true, golden: "output/schema-negative.txt", }, // Install, values from yaml, extra values from yaml, schematized with errors { name: "install with schema file, extra values from yaml, with errors", cmd: "install schema testdata/testcharts/chart-with-schema -f testdata/testcharts/chart-with-schema/extra-values.yaml", wantError: true, golden: "output/schema-negative.txt", }, // Install, values from yaml, extra values from cli, schematized with errors { name: "install with schema file, extra values from cli, with errors", cmd: "install schema testdata/testcharts/chart-with-schema --set age=-5", wantError: true, golden: "output/schema-negative-cli.txt", }, // Install with subchart, values from yaml, schematized with errors { name: "install with schema file and schematized subchart, with errors", cmd: "install schema testdata/testcharts/chart-with-schema-and-subchart", wantError: true, golden: "output/subchart-schema-negative.txt", }, // Install with subchart, values from yaml, extra values from cli, schematized with errors { name: "install with schema file and schematized subchart, extra values from cli", cmd: "install schema testdata/testcharts/chart-with-schema-and-subchart --set lastname=doe --set subchart-with-schema.age=25", golden: "output/subchart-schema-cli.txt", }, // Install with subchart, values from yaml, extra values from cli, schematized with errors { name: "install with schema file and schematized subchart, extra values from cli, with errors", cmd: "install schema testdata/testcharts/chart-with-schema-and-subchart --set lastname=doe --set subchart-with-schema.age=-25", wantError: true, golden: "output/subchart-schema-cli-negative.txt", }, // Install, values from yaml, schematized with errors but skip schema validation, expect success { name: "install with schema file and schematized subchart, extra values from cli, skip schema validation", cmd: "install schema testdata/testcharts/chart-with-schema-and-subchart --set lastname=doe --set subchart-with-schema.age=-25 --skip-schema-validation", golden: "output/schema.txt", }, // Install deprecated chart { name: "install with warning about deprecated chart", cmd: "install aeneas testdata/testcharts/deprecated --namespace default", golden: "output/deprecated-chart.txt", }, // Install chart with only crds { name: "install chart with only crds", cmd: "install crd-test testdata/testcharts/chart-with-only-crds --namespace default", }, // Verify the user/pass works { name: "basic install with credentials", cmd: "install aeneas reqtest --namespace default --repo " + srv.URL() + " --username username --password password", golden: "output/install.txt", }, { name: "basic install with credentials", cmd: "install aeneas reqtest --namespace default --repo " + srv2.URL + " --username username --password password --pass-credentials", golden: "output/install.txt", }, { name: "basic install with credentials and no repo", cmd: fmt.Sprintf("install aeneas test/reqtest --username username --password password --repository-config %s --repository-cache %s", repoFile, srv.Root()), golden: "output/install.txt", }, { name: "dry-run displaying secret", cmd: "install secrets testdata/testcharts/chart-with-secret --dry-run", golden: "output/install-dry-run-with-secret.txt", }, { name: "dry-run hiding secret", cmd: "install secrets testdata/testcharts/chart-with-secret --dry-run --hide-secret", golden: "output/install-dry-run-with-secret-hidden.txt", }, { name: "hide-secret error without dry-run", cmd: "install secrets testdata/testcharts/chart-with-secret --hide-secret", wantError: true, golden: "output/install-hide-secret.txt", }, } runTestCmd(t, tests) } func TestInstallOutputCompletion(t *testing.T) { outputFlagCompletionTest(t, "install") } func TestInstallVersionCompletion(t *testing.T) { repoFile := "testdata/helmhome/helm/repositories.yaml" repoCache := "testdata/helmhome/helm/repository" repoSetup := fmt.Sprintf("--repository-config %s --repository-cache %s", repoFile, repoCache) tests := []cmdTestCase{{ name: "completion for install version flag with release name", cmd: fmt.Sprintf("%s __complete install releasename testing/alpine --version ''", repoSetup), golden: "output/version-comp.txt", }, { name: "completion for install version flag with generate-name", cmd: fmt.Sprintf("%s __complete install --generate-name testing/alpine --version ''", repoSetup), golden: "output/version-comp.txt", }, { name: "completion for install version flag, no filter", cmd: fmt.Sprintf("%s __complete install releasename testing/alpine --version 0.3", repoSetup), golden: "output/version-comp.txt", }, { name: "completion for install version flag too few args", cmd: fmt.Sprintf("%s __complete install testing/alpine --version ''", repoSetup), golden: "output/version-invalid-comp.txt", }, { name: "completion for install version flag too many args", cmd: fmt.Sprintf("%s __complete install releasename testing/alpine badarg --version ''", repoSetup), golden: "output/version-invalid-comp.txt", }, { name: "completion for install version flag invalid chart", cmd: fmt.Sprintf("%s __complete install releasename invalid/invalid --version ''", repoSetup), golden: "output/version-invalid-comp.txt", }} runTestCmd(t, tests) } func TestInstallFileCompletion(t *testing.T) { checkFileCompletion(t, "install", false) checkFileCompletion(t, "install --generate-name", true) checkFileCompletion(t, "install myname", true) checkFileCompletion(t, "install myname mychart", false) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/get_manifest_test.go
pkg/cmd/get_manifest_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "testing" release "helm.sh/helm/v4/pkg/release/v1" ) func TestGetManifest(t *testing.T) { tests := []cmdTestCase{{ name: "get manifest with release", cmd: "get manifest juno", golden: "output/get-manifest.txt", rels: []*release.Release{release.Mock(&release.MockReleaseOptions{Name: "juno"})}, }, { name: "get manifest without args", cmd: "get manifest", golden: "output/get-manifest-no-args.txt", wantError: true, }} runTestCmd(t, tests) } func TestGetManifestCompletion(t *testing.T) { checkReleaseCompletion(t, "get manifest", false) } func TestGetManifestRevisionCompletion(t *testing.T) { revisionFlagCompletionTest(t, "get manifest") } func TestGetManifestFileCompletion(t *testing.T) { checkFileCompletion(t, "get manifest", false) checkFileCompletion(t, "get manifest myrelease", false) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/search_hub.go
pkg/cmd/search_hub.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "io" "log/slog" "strings" "github.com/gosuri/uitable" "github.com/spf13/cobra" "helm.sh/helm/v4/internal/monocular" "helm.sh/helm/v4/pkg/cli/output" ) const searchHubDesc = ` Search for Helm charts in the Artifact Hub or your own hub instance. Artifact Hub is a web-based application that enables finding, installing, and publishing packages and configurations for CNCF projects, including publicly available distributed charts Helm charts. It is a Cloud Native Computing Foundation sandbox project. You can browse the hub at https://artifacthub.io/ The [KEYWORD] argument accepts either a keyword string, or quoted string of rich query options. For rich query options documentation, see https://artifacthub.github.io/hub/api/?urls.primaryName=Monocular%20compatible%20search%20API#/Monocular/get_api_chartsvc_v1_charts_search Previous versions of Helm used an instance of Monocular as the default 'endpoint', so for backwards compatibility Artifact Hub is compatible with the Monocular search API. Similarly, when setting the 'endpoint' flag, the specified endpoint must also be implement a Monocular compatible search API endpoint. Note that when specifying a Monocular instance as the 'endpoint', rich queries are not supported. For API details, see https://github.com/helm/monocular ` type searchHubOptions struct { searchEndpoint string maxColWidth uint outputFormat output.Format listRepoURL bool failOnNoResult bool } func newSearchHubCmd(out io.Writer) *cobra.Command { o := &searchHubOptions{} cmd := &cobra.Command{ Use: "hub [KEYWORD]", Short: "search for charts in the Artifact Hub or your own hub instance", Long: searchHubDesc, RunE: func(_ *cobra.Command, args []string) error { return o.run(out, args) }, } f := cmd.Flags() f.StringVar(&o.searchEndpoint, "endpoint", "https://hub.helm.sh", "Hub instance to query for charts") f.UintVar(&o.maxColWidth, "max-col-width", 50, "maximum column width for output table") f.BoolVar(&o.listRepoURL, "list-repo-url", false, "print charts repository URL") f.BoolVar(&o.failOnNoResult, "fail-on-no-result", false, "search fails if no results are found") bindOutputFlag(cmd, &o.outputFormat) return cmd } func (o *searchHubOptions) run(out io.Writer, args []string) error { c, err := monocular.New(o.searchEndpoint) if err != nil { return fmt.Errorf("unable to create connection to %q: %w", o.searchEndpoint, err) } q := strings.Join(args, " ") results, err := c.Search(q) if err != nil { slog.Debug("search failed", slog.Any("error", err)) return fmt.Errorf("unable to perform search against %q", o.searchEndpoint) } return o.outputFormat.Write(out, newHubSearchWriter(results, o.searchEndpoint, o.maxColWidth, o.listRepoURL, o.failOnNoResult)) } type hubChartRepo struct { URL string `json:"url"` Name string `json:"name"` } type hubChartElement struct { URL string `json:"url"` Version string `json:"version"` AppVersion string `json:"app_version"` Description string `json:"description"` Repository hubChartRepo `json:"repository"` } type hubSearchWriter struct { elements []hubChartElement columnWidth uint listRepoURL bool failOnNoResult bool } func newHubSearchWriter(results []monocular.SearchResult, endpoint string, columnWidth uint, listRepoURL, failOnNoResult bool) *hubSearchWriter { var elements []hubChartElement for _, r := range results { // Backwards compatibility for Monocular url := endpoint + "/charts/" + r.ID // Check for artifactHub compatibility if r.ArtifactHub.PackageURL != "" { url = r.ArtifactHub.PackageURL } elements = append(elements, hubChartElement{url, r.Relationships.LatestChartVersion.Data.Version, r.Relationships.LatestChartVersion.Data.AppVersion, r.Attributes.Description, hubChartRepo{URL: r.Attributes.Repo.URL, Name: r.Attributes.Repo.Name}}) } return &hubSearchWriter{elements, columnWidth, listRepoURL, failOnNoResult} } func (h *hubSearchWriter) WriteTable(out io.Writer) error { if len(h.elements) == 0 { // Fail if no results found and --fail-on-no-result is enabled if h.failOnNoResult { return fmt.Errorf("no results found") } _, err := out.Write([]byte("No results found\n")) if err != nil { return fmt.Errorf("unable to write results: %s", err) } return nil } table := uitable.New() table.MaxColWidth = h.columnWidth if h.listRepoURL { table.AddRow("URL", "CHART VERSION", "APP VERSION", "DESCRIPTION", "REPO URL") } else { table.AddRow("URL", "CHART VERSION", "APP VERSION", "DESCRIPTION") } for _, r := range h.elements { if h.listRepoURL { table.AddRow(r.URL, r.Version, r.AppVersion, r.Description, r.Repository.URL) } else { table.AddRow(r.URL, r.Version, r.AppVersion, r.Description) } } return output.EncodeTable(out, table) } func (h *hubSearchWriter) WriteJSON(out io.Writer) error { return h.encodeByFormat(out, output.JSON) } func (h *hubSearchWriter) WriteYAML(out io.Writer) error { return h.encodeByFormat(out, output.YAML) } func (h *hubSearchWriter) encodeByFormat(out io.Writer, format output.Format) error { // Fail if no results found and --fail-on-no-result is enabled if len(h.elements) == 0 && h.failOnNoResult { return fmt.Errorf("no results found") } // Initialize the array so no results returns an empty array instead of null chartList := make([]hubChartElement, 0, len(h.elements)) for _, r := range h.elements { chartList = append(chartList, hubChartElement{r.URL, r.Version, r.AppVersion, r.Description, r.Repository}) } switch format { case output.JSON: return output.EncodeJSON(out, chartList) case output.YAML: return output.EncodeYAML(out, chartList) default: // Because this is a non-exported function and only called internally by // WriteJSON and WriteYAML, we shouldn't get invalid types return nil } }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/history.go
pkg/cmd/history.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "encoding/json" "fmt" "io" "strconv" "time" "github.com/gosuri/uitable" "github.com/spf13/cobra" "helm.sh/helm/v4/pkg/action" chart "helm.sh/helm/v4/pkg/chart/v2" "helm.sh/helm/v4/pkg/cli/output" "helm.sh/helm/v4/pkg/cmd/require" release "helm.sh/helm/v4/pkg/release/v1" releaseutil "helm.sh/helm/v4/pkg/release/v1/util" ) var historyHelp = ` History prints historical revisions for a given release. A default maximum of 256 revisions will be returned. Setting '--max' configures the maximum length of the revision list returned. The historical release set is printed as a formatted table, e.g: $ helm history angry-bird REVISION UPDATED STATUS CHART APP VERSION DESCRIPTION 1 Mon Oct 3 10:15:13 2016 superseded alpine-0.1.0 1.0 Initial install 2 Mon Oct 3 10:15:13 2016 superseded alpine-0.1.0 1.0 Upgraded successfully 3 Mon Oct 3 10:15:13 2016 superseded alpine-0.1.0 1.0 Rolled back to 2 4 Mon Oct 3 10:15:13 2016 deployed alpine-0.1.0 1.0 Upgraded successfully ` func newHistoryCmd(cfg *action.Configuration, out io.Writer) *cobra.Command { client := action.NewHistory(cfg) var outfmt output.Format cmd := &cobra.Command{ Use: "history RELEASE_NAME", Long: historyHelp, Short: "fetch release history", Aliases: []string{"hist"}, Args: require.ExactArgs(1), ValidArgsFunction: func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { if len(args) != 0 { return noMoreArgsComp() } return compListReleases(toComplete, args, cfg) }, RunE: func(_ *cobra.Command, args []string) error { history, err := getHistory(client, args[0]) if err != nil { return err } return outfmt.Write(out, history) }, } f := cmd.Flags() f.IntVar(&client.Max, "max", 256, "maximum number of revision to include in history") bindOutputFlag(cmd, &outfmt) return cmd } type releaseInfo struct { Revision int `json:"revision"` Updated time.Time `json:"updated,omitzero"` Status string `json:"status"` Chart string `json:"chart"` AppVersion string `json:"app_version"` Description string `json:"description"` } // releaseInfoJSON is used for custom JSON marshaling/unmarshaling type releaseInfoJSON struct { Revision int `json:"revision"` Updated *time.Time `json:"updated,omitempty"` Status string `json:"status"` Chart string `json:"chart"` AppVersion string `json:"app_version"` Description string `json:"description"` } // UnmarshalJSON implements the json.Unmarshaler interface. // It handles empty string time fields by treating them as zero values. func (r *releaseInfo) UnmarshalJSON(data []byte) error { // First try to unmarshal into a map to handle empty string time fields var raw map[string]interface{} if err := json.Unmarshal(data, &raw); err != nil { return err } // Replace empty string time fields with nil if val, ok := raw["updated"]; ok { if str, ok := val.(string); ok && str == "" { raw["updated"] = nil } } // Re-marshal with cleaned data cleaned, err := json.Marshal(raw) if err != nil { return err } // Unmarshal into temporary struct with pointer time field var tmp releaseInfoJSON if err := json.Unmarshal(cleaned, &tmp); err != nil { return err } // Copy values to releaseInfo struct r.Revision = tmp.Revision if tmp.Updated != nil { r.Updated = *tmp.Updated } r.Status = tmp.Status r.Chart = tmp.Chart r.AppVersion = tmp.AppVersion r.Description = tmp.Description return nil } // MarshalJSON implements the json.Marshaler interface. // It omits zero-value time fields from the JSON output. func (r releaseInfo) MarshalJSON() ([]byte, error) { tmp := releaseInfoJSON{ Revision: r.Revision, Status: r.Status, Chart: r.Chart, AppVersion: r.AppVersion, Description: r.Description, } if !r.Updated.IsZero() { tmp.Updated = &r.Updated } return json.Marshal(tmp) } type releaseHistory []releaseInfo func (r releaseHistory) WriteJSON(out io.Writer) error { return output.EncodeJSON(out, r) } func (r releaseHistory) WriteYAML(out io.Writer) error { return output.EncodeYAML(out, r) } func (r releaseHistory) WriteTable(out io.Writer) error { tbl := uitable.New() tbl.AddRow("REVISION", "UPDATED", "STATUS", "CHART", "APP VERSION", "DESCRIPTION") for _, item := range r { tbl.AddRow(item.Revision, item.Updated.Format(time.ANSIC), item.Status, item.Chart, item.AppVersion, item.Description) } return output.EncodeTable(out, tbl) } func getHistory(client *action.History, name string) (releaseHistory, error) { histi, err := client.Run(name) if err != nil { return nil, err } hist, err := releaseListToV1List(histi) if err != nil { return nil, err } releaseutil.Reverse(hist, releaseutil.SortByRevision) var rels []*release.Release for i := 0; i < min(len(hist), client.Max); i++ { rels = append(rels, hist[i]) } if len(rels) == 0 { return releaseHistory{}, nil } releaseHistory := getReleaseHistory(rels) return releaseHistory, nil } func getReleaseHistory(rls []*release.Release) (history releaseHistory) { for i := len(rls) - 1; i >= 0; i-- { r := rls[i] c := formatChartName(r.Chart) s := r.Info.Status.String() v := r.Version d := r.Info.Description a := formatAppVersion(r.Chart) rInfo := releaseInfo{ Revision: v, Status: s, Chart: c, AppVersion: a, Description: d, } if !r.Info.LastDeployed.IsZero() { rInfo.Updated = r.Info.LastDeployed } history = append(history, rInfo) } return history } func formatChartName(c *chart.Chart) string { if c == nil || c.Metadata == nil { // This is an edge case that has happened in prod, though we don't // know how: https://github.com/helm/helm/issues/1347 return "MISSING" } return fmt.Sprintf("%s-%s", c.Name(), c.Metadata.Version) } func formatAppVersion(c *chart.Chart) string { if c == nil || c.Metadata == nil { // This is an edge case that has happened in prod, though we don't // know how: https://github.com/helm/helm/issues/1347 return "MISSING" } return c.AppVersion() } func compListRevisions(_ string, cfg *action.Configuration, releaseName string) ([]string, cobra.ShellCompDirective) { client := action.NewHistory(cfg) var revisions []string if histi, err := client.Run(releaseName); err == nil { hist, err := releaseListToV1List(histi) if err != nil { return nil, cobra.ShellCompDirectiveError } for _, version := range hist { appVersion := fmt.Sprintf("App: %s", version.Chart.Metadata.AppVersion) chartDesc := fmt.Sprintf("Chart: %s-%s", version.Chart.Metadata.Name, version.Chart.Metadata.Version) revisions = append(revisions, fmt.Sprintf("%s\t%s, %s", strconv.Itoa(version.Version), appVersion, chartDesc)) } return revisions, cobra.ShellCompDirectiveNoFileComp } return nil, cobra.ShellCompDirectiveError }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/plugin_verify_test.go
pkg/cmd/plugin_verify_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "bytes" "crypto/sha256" "fmt" "os" "path/filepath" "strings" "testing" "helm.sh/helm/v4/internal/plugin" "helm.sh/helm/v4/internal/test/ensure" ) func TestPluginVerifyCmd_NoArgs(t *testing.T) { ensure.HelmHome(t) out := &bytes.Buffer{} cmd := newPluginVerifyCmd(out) cmd.SetArgs([]string{}) err := cmd.Execute() if err == nil { t.Error("expected error when no arguments provided") } if !strings.Contains(err.Error(), "requires 1 argument") { t.Errorf("expected 'requires 1 argument' error, got: %v", err) } } func TestPluginVerifyCmd_TooManyArgs(t *testing.T) { ensure.HelmHome(t) out := &bytes.Buffer{} cmd := newPluginVerifyCmd(out) cmd.SetArgs([]string{"plugin1", "plugin2"}) err := cmd.Execute() if err == nil { t.Error("expected error when too many arguments provided") } if !strings.Contains(err.Error(), "requires 1 argument") { t.Errorf("expected 'requires 1 argument' error, got: %v", err) } } func TestPluginVerifyCmd_NonexistentFile(t *testing.T) { ensure.HelmHome(t) out := &bytes.Buffer{} cmd := newPluginVerifyCmd(out) cmd.SetArgs([]string{"/nonexistent/plugin.tgz"}) err := cmd.Execute() if err == nil { t.Error("expected error when plugin file doesn't exist") } } func TestPluginVerifyCmd_MissingProvenance(t *testing.T) { ensure.HelmHome(t) // Create a plugin tarball without .prov file pluginTgz := createTestPluginTarball(t) defer os.Remove(pluginTgz) out := &bytes.Buffer{} cmd := newPluginVerifyCmd(out) cmd.SetArgs([]string{pluginTgz}) err := cmd.Execute() if err == nil { t.Error("expected error when .prov file is missing") } if !strings.Contains(err.Error(), "could not find provenance file") { t.Errorf("expected 'could not find provenance file' error, got: %v", err) } } func TestPluginVerifyCmd_InvalidProvenance(t *testing.T) { ensure.HelmHome(t) // Create a plugin tarball with invalid .prov file pluginTgz := createTestPluginTarball(t) defer os.Remove(pluginTgz) // Create invalid .prov file provFile := pluginTgz + ".prov" if err := os.WriteFile(provFile, []byte("invalid provenance"), 0644); err != nil { t.Fatal(err) } defer os.Remove(provFile) out := &bytes.Buffer{} cmd := newPluginVerifyCmd(out) cmd.SetArgs([]string{pluginTgz}) err := cmd.Execute() if err == nil { t.Error("expected error when .prov file is invalid") } } func TestPluginVerifyCmd_DirectoryNotSupported(t *testing.T) { ensure.HelmHome(t) // Create a plugin directory pluginDir := createTestPluginDir(t) out := &bytes.Buffer{} cmd := newPluginVerifyCmd(out) cmd.SetArgs([]string{pluginDir}) err := cmd.Execute() if err == nil { t.Error("expected error when verifying directory") } if !strings.Contains(err.Error(), "directory verification not supported") { t.Errorf("expected 'directory verification not supported' error, got: %v", err) } } func TestPluginVerifyCmd_KeyringFlag(t *testing.T) { ensure.HelmHome(t) // Create a plugin tarball with .prov file pluginTgz := createTestPluginTarball(t) defer os.Remove(pluginTgz) // Create .prov file provFile := pluginTgz + ".prov" createProvFile(t, provFile, pluginTgz, "") defer os.Remove(provFile) // Create empty keyring file keyring := createTestKeyring(t) defer os.Remove(keyring) out := &bytes.Buffer{} cmd := newPluginVerifyCmd(out) cmd.SetArgs([]string{"--keyring", keyring, pluginTgz}) // Should fail with keyring error but command parsing should work err := cmd.Execute() if err == nil { t.Error("expected error with empty keyring") } // The important thing is that the keyring flag was parsed and used } func TestPluginVerifyOptions_Run_Success(t *testing.T) { // Skip this test as it would require real PGP keys and valid signatures // The core verification logic is thoroughly tested in internal/plugin/verify_test.go t.Skip("Success case requires real PGP keys - core logic tested in internal/plugin/verify_test.go") } // Helper functions for test setup func createTestPluginDir(t *testing.T) string { t.Helper() // Create temporary directory with plugin structure tmpDir := t.TempDir() pluginDir := filepath.Join(tmpDir, "test-plugin") if err := os.MkdirAll(pluginDir, 0755); err != nil { t.Fatalf("Failed to create plugin directory: %v", err) } // Use the same plugin YAML as other cmd tests if err := os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(testPluginYAML), 0644); err != nil { t.Fatalf("Failed to create plugin.yaml: %v", err) } return pluginDir } func createTestPluginTarball(t *testing.T) string { t.Helper() pluginDir := createTestPluginDir(t) // Create tarball using the plugin package helper tmpDir := filepath.Dir(pluginDir) tgzPath := filepath.Join(tmpDir, "test-plugin-1.0.0.tgz") tarFile, err := os.Create(tgzPath) if err != nil { t.Fatalf("Failed to create tarball file: %v", err) } defer tarFile.Close() if err := plugin.CreatePluginTarball(pluginDir, "test-plugin", tarFile); err != nil { t.Fatalf("Failed to create tarball: %v", err) } return tgzPath } func createProvFile(t *testing.T, provFile, pluginTgz, hash string) { t.Helper() var hashStr string if hash == "" { // Calculate actual hash of the tarball data, err := os.ReadFile(pluginTgz) if err != nil { t.Fatalf("Failed to read tarball for hashing: %v", err) } hashSum := sha256.Sum256(data) hashStr = fmt.Sprintf("sha256:%x", hashSum) } else { // Use provided hash hashStr = hash } // Create properly formatted provenance file with specified hash provContent := fmt.Sprintf(`-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA256 name: test-plugin version: 1.0.0 description: Test plugin for verification files: test-plugin-1.0.0.tgz: %s -----BEGIN PGP SIGNATURE----- Version: GnuPG v1 iQEcBAEBCAAGBQJktest... -----END PGP SIGNATURE----- `, hashStr) if err := os.WriteFile(provFile, []byte(provContent), 0644); err != nil { t.Fatalf("Failed to create provenance file: %v", err) } } func createTestKeyring(t *testing.T) string { t.Helper() // Create a temporary keyring file tmpDir := t.TempDir() keyringPath := filepath.Join(tmpDir, "pubring.gpg") // Create empty keyring for testing if err := os.WriteFile(keyringPath, []byte{}, 0644); err != nil { t.Fatalf("Failed to create test keyring: %v", err) } return keyringPath }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/release_testing.go
pkg/cmd/release_testing.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "errors" "fmt" "io" "regexp" "strings" "time" "github.com/spf13/cobra" "helm.sh/helm/v4/pkg/action" "helm.sh/helm/v4/pkg/cli/output" "helm.sh/helm/v4/pkg/cmd/require" ) const releaseTestHelp = ` The test command runs the tests for a release. The argument this command takes is the name of a deployed release. The tests to be run are defined in the chart that was installed. ` func newReleaseTestCmd(cfg *action.Configuration, out io.Writer) *cobra.Command { client := action.NewReleaseTesting(cfg) outfmt := output.Table var outputLogs bool var filter []string cmd := &cobra.Command{ Use: "test [RELEASE]", Short: "run tests for a release", Long: releaseTestHelp, Args: require.ExactArgs(1), ValidArgsFunction: func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { if len(args) != 0 { return noMoreArgsComp() } return compListReleases(toComplete, args, cfg) }, RunE: func(_ *cobra.Command, args []string) error { client.Namespace = settings.Namespace() notName := regexp.MustCompile(`^!\s?name=`) for _, f := range filter { if after, ok := strings.CutPrefix(f, "name="); ok { client.Filters[action.IncludeNameFilter] = append(client.Filters[action.IncludeNameFilter], after) } else if notName.MatchString(f) { client.Filters[action.ExcludeNameFilter] = append(client.Filters[action.ExcludeNameFilter], notName.ReplaceAllLiteralString(f, "")) } } reli, runErr := client.Run(args[0]) // 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 // if requested if runErr != nil && reli == nil { return runErr } rel, err := releaserToV1Release(reli) if err != nil { return err } if err := outfmt.Write(out, &statusPrinter{ release: rel, debug: settings.Debug, showMetadata: false, hideNotes: true, noColor: settings.ShouldDisableColor(), }); err != nil { return err } if outputLogs { // Print a newline to stdout to separate the output fmt.Fprintln(out) if err := client.GetPodLogs(out, rel); err != nil { return errors.Join(runErr, err) } } return runErr }, } f := cmd.Flags() f.DurationVar(&client.Timeout, "timeout", 300*time.Second, "time to wait for any individual Kubernetes operation (like Jobs for hooks)") f.BoolVar(&outputLogs, "logs", false, "dump the logs from test pods (this runs after all tests are complete, but before any cleanup)") f.StringSliceVar(&filter, "filter", []string{}, "specify tests by attribute (currently \"name\") using attribute=value syntax or '!attribute=value' to exclude a test (can specify multiple or separate values with commas: name=test1,name=test2)") return cmd }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/package_test.go
pkg/cmd/package_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "os" "path/filepath" "regexp" "strings" "testing" "helm.sh/helm/v4/internal/test/ensure" chart "helm.sh/helm/v4/pkg/chart/v2" "helm.sh/helm/v4/pkg/chart/v2/loader" ) func TestPackage(t *testing.T) { tests := []struct { name string flags map[string]string args []string expect string hasfile string err bool }{ { name: "package without chart path", args: []string{}, flags: map[string]string{}, expect: "need at least one argument, the path to the chart", err: true, }, { name: "package --sign, no --key", args: []string{"testdata/testcharts/alpine"}, flags: map[string]string{"sign": "1"}, expect: "key is required for signing a package", err: true, }, { name: "package --sign, no --keyring", args: []string{"testdata/testcharts/alpine"}, flags: map[string]string{"sign": "1", "key": "nosuchkey", "keyring": ""}, expect: "keyring is required for signing a package", err: true, }, { name: "package testdata/testcharts/alpine, no save", args: []string{"testdata/testcharts/alpine"}, flags: map[string]string{"save": "0"}, expect: "", hasfile: "alpine-0.1.0.tgz", }, { name: "package testdata/testcharts/alpine", args: []string{"testdata/testcharts/alpine"}, expect: "", hasfile: "alpine-0.1.0.tgz", }, { name: "package testdata/testcharts/issue1979", args: []string{"testdata/testcharts/issue1979"}, expect: "", hasfile: "alpine-0.1.0.tgz", }, { name: "package --destination toot", args: []string{"testdata/testcharts/alpine"}, flags: map[string]string{"destination": "toot"}, expect: "", hasfile: "toot/alpine-0.1.0.tgz", }, { name: "package --sign --key=KEY --keyring=KEYRING testdata/testcharts/alpine", args: []string{"testdata/testcharts/alpine"}, flags: map[string]string{"sign": "1", "keyring": "testdata/helm-test-key.secret", "key": "helm-test"}, expect: "", hasfile: "alpine-0.1.0.tgz", }, { name: "package testdata/testcharts/chart-missing-deps", args: []string{"testdata/testcharts/chart-missing-deps"}, hasfile: "chart-missing-deps-0.1.0.tgz", err: true, }, { name: "package testdata/testcharts/chart-bad-type", args: []string{"testdata/testcharts/chart-bad-type"}, err: true, }, } origDir, err := os.Getwd() if err != nil { t.Fatal(err) } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Chdir(t.TempDir()) ensure.HelmHome(t) if err := os.MkdirAll("toot", 0o777); err != nil { t.Fatal(err) } // This is an unfortunate byproduct of the tmpdir if v, ok := tt.flags["keyring"]; ok && len(v) > 0 { tt.flags["keyring"] = filepath.Join(origDir, v) } re := regexp.MustCompile(tt.expect) adjustedArgs := make([]string, len(tt.args)) for i, f := range tt.args { adjustedArgs[i] = filepath.Join(origDir, f) } cmd := []string{"package"} if len(adjustedArgs) > 0 { cmd = append(cmd, adjustedArgs...) } for k, v := range tt.flags { if v != "0" { cmd = append(cmd, fmt.Sprintf("--%s=%s", k, v)) } } _, _, err = executeActionCommand(strings.Join(cmd, " ")) if err != nil { if tt.err && re.MatchString(err.Error()) { return } t.Fatalf("%q: expected error %q, got %q", tt.name, tt.expect, err) } if len(tt.hasfile) > 0 { if fi, err := os.Stat(tt.hasfile); err != nil { t.Errorf("%q: expected file %q, got err %q", tt.name, tt.hasfile, err) } else if fi.Size() == 0 { t.Errorf("%q: file %q has zero bytes.", tt.name, tt.hasfile) } } if v, ok := tt.flags["sign"]; ok && v == "1" { if fi, err := os.Stat(tt.hasfile + ".prov"); err != nil { t.Errorf("%q: expected provenance file", tt.name) } else if fi.Size() == 0 { t.Errorf("%q: provenance file is empty", tt.name) } } }) } } func TestSetAppVersion(t *testing.T) { var ch *chart.Chart expectedAppVersion := "app-version-foo" chartToPackage := "testdata/testcharts/alpine" dir := t.TempDir() cmd := fmt.Sprintf("package %s --destination=%s --app-version=%s", chartToPackage, dir, expectedAppVersion) _, output, err := executeActionCommand(cmd) if err != nil { t.Logf("Output: %s", output) t.Fatal(err) } chartPath := filepath.Join(dir, "alpine-0.1.0.tgz") if fi, err := os.Stat(chartPath); err != nil { t.Errorf("expected file %q, got err %q", chartPath, err) } else if fi.Size() == 0 { t.Errorf("file %q has zero bytes.", chartPath) } ch, err = loader.Load(chartPath) if err != nil { t.Fatalf("unexpected error loading packaged chart: %v", err) } if ch.Metadata.AppVersion != expectedAppVersion { t.Errorf("expected app-version %q, found %q", expectedAppVersion, ch.Metadata.AppVersion) } } func TestPackageFileCompletion(t *testing.T) { checkFileCompletion(t, "package", true) checkFileCompletion(t, "package mypath", true) // Multiple paths can be given }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/search.go
pkg/cmd/search.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "io" "github.com/spf13/cobra" ) const searchDesc = ` Search provides the ability to search for Helm charts in the various places they can be stored including the Artifact Hub and repositories you have added. Use search subcommands to search different locations for charts. ` func newSearchCmd(out io.Writer) *cobra.Command { cmd := &cobra.Command{ Use: "search [keyword]", Short: "search for a keyword in charts", Long: searchDesc, } cmd.AddCommand(newSearchHubCmd(out)) cmd.AddCommand(newSearchRepoCmd(out)) return cmd }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/show_test.go
pkg/cmd/show_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "path/filepath" "strings" "testing" "helm.sh/helm/v4/pkg/repo/v1/repotest" ) func TestShowPreReleaseChart(t *testing.T) { srv := repotest.NewTempServer( t, repotest.WithChartSourceGlob("testdata/testcharts/*.tgz*"), ) defer srv.Stop() if err := srv.LinkIndices(); err != nil { t.Fatal(err) } tests := []struct { name string args string flags string fail bool expectedErr string }{ { name: "show pre-release chart", args: "test/pre-release-chart", fail: true, expectedErr: "chart \"pre-release-chart\" matching not found in test index. (try 'helm repo update'): no chart version found for pre-release-chart-", }, { name: "show pre-release chart", args: "test/pre-release-chart", fail: true, flags: "--version 1.0.0", expectedErr: "chart \"pre-release-chart\" matching 1.0.0 not found in test index. (try 'helm repo update'): no chart version found for pre-release-chart-1.0.0", }, { name: "show pre-release chart with 'devel' flag", args: "test/pre-release-chart", flags: "--devel", fail: false, }, } contentTmp := t.TempDir() for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { outdir := srv.Root() cmd := fmt.Sprintf("show all '%s' %s --repository-config %s --repository-cache %s --content-cache %s", tt.args, tt.flags, filepath.Join(outdir, "repositories.yaml"), outdir, contentTmp, ) //_, out, err := executeActionCommand(cmd) _, _, err := executeActionCommand(cmd) if err != nil { if tt.fail { if !strings.Contains(err.Error(), tt.expectedErr) { t.Errorf("%q expected error: %s, got: %s", tt.name, tt.expectedErr, err.Error()) } return } t.Errorf("%q reported error: %s", tt.name, err) } }) } } func TestShowVersionCompletion(t *testing.T) { repoFile := "testdata/helmhome/helm/repositories.yaml" repoCache := "testdata/helmhome/helm/repository" repoSetup := fmt.Sprintf("--repository-config %s --repository-cache %s", repoFile, repoCache) tests := []cmdTestCase{{ name: "completion for show version flag", cmd: fmt.Sprintf("%s __complete show chart testing/alpine --version ''", repoSetup), golden: "output/version-comp.txt", }, { name: "completion for show version flag, no filter", cmd: fmt.Sprintf("%s __complete show chart testing/alpine --version 0.3", repoSetup), golden: "output/version-comp.txt", }, { name: "completion for show version flag too few args", cmd: fmt.Sprintf("%s __complete show chart --version ''", repoSetup), golden: "output/version-invalid-comp.txt", }, { name: "completion for show version flag too many args", cmd: fmt.Sprintf("%s __complete show chart testing/alpine badarg --version ''", repoSetup), golden: "output/version-invalid-comp.txt", }, { name: "completion for show version flag invalid chart", cmd: fmt.Sprintf("%s __complete show chart invalid/invalid --version ''", repoSetup), golden: "output/version-invalid-comp.txt", }, { name: "completion for show version flag with all", cmd: fmt.Sprintf("%s __complete show all testing/alpine --version ''", repoSetup), golden: "output/version-comp.txt", }, { name: "completion for show version flag with readme", cmd: fmt.Sprintf("%s __complete show readme testing/alpine --version ''", repoSetup), golden: "output/version-comp.txt", }, { name: "completion for show version flag with values", cmd: fmt.Sprintf("%s __complete show values testing/alpine --version ''", repoSetup), golden: "output/version-comp.txt", }} runTestCmd(t, tests) } func TestShowFileCompletion(t *testing.T) { checkFileCompletion(t, "show", false) } func TestShowAllFileCompletion(t *testing.T) { checkFileCompletion(t, "show all", true) } func TestShowChartFileCompletion(t *testing.T) { checkFileCompletion(t, "show chart", true) } func TestShowReadmeFileCompletion(t *testing.T) { checkFileCompletion(t, "show readme", true) } func TestShowValuesFileCompletion(t *testing.T) { checkFileCompletion(t, "show values", true) } func TestShowCRDsFileCompletion(t *testing.T) { checkFileCompletion(t, "show crds", true) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/docs.go
pkg/cmd/docs.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "io" "path" "path/filepath" "strings" "github.com/spf13/cobra" "github.com/spf13/cobra/doc" "golang.org/x/text/cases" "golang.org/x/text/language" "helm.sh/helm/v4/pkg/cmd/require" ) const docsDesc = ` Generate documentation files for Helm. This command can generate documentation for Helm in the following formats: - Markdown - Man pages It can also generate bash autocompletions. ` type docsOptions struct { dest string docTypeString string topCmd *cobra.Command generateHeaders bool } func newDocsCmd(out io.Writer) *cobra.Command { o := &docsOptions{} cmd := &cobra.Command{ Use: "docs", Short: "generate documentation as markdown or man pages", Long: docsDesc, Hidden: true, Args: require.NoArgs, ValidArgsFunction: noMoreArgsCompFunc, RunE: func(cmd *cobra.Command, _ []string) error { o.topCmd = cmd.Root() return o.run(out) }, } f := cmd.Flags() f.StringVar(&o.dest, "dir", "./", "directory to which documentation is written") f.StringVar(&o.docTypeString, "type", "markdown", "the type of documentation to generate (markdown, man, bash)") f.BoolVar(&o.generateHeaders, "generate-headers", false, "generate standard headers for markdown files") cmd.RegisterFlagCompletionFunc("type", func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) { return []string{"bash", "man", "markdown"}, cobra.ShellCompDirectiveNoFileComp }) return cmd } func (o *docsOptions) run(_ io.Writer) error { switch o.docTypeString { case "markdown", "mdown", "md": if o.generateHeaders { standardLinks := func(s string) string { return s } hdrFunc := func(filename string) string { base := filepath.Base(filename) name := strings.TrimSuffix(base, path.Ext(base)) title := cases.Title(language.Und, cases.NoLower).String(strings.ReplaceAll(name, "_", " ")) return fmt.Sprintf("---\ntitle: \"%s\"\n---\n\n", title) } return doc.GenMarkdownTreeCustom(o.topCmd, o.dest, hdrFunc, standardLinks) } return doc.GenMarkdownTree(o.topCmd, o.dest) case "man": manHdr := &doc.GenManHeader{Title: "HELM", Section: "1"} return doc.GenManTree(o.topCmd, manHdr, o.dest) case "bash": return o.topCmd.GenBashCompletionFile(filepath.Join(o.dest, "completions.bash")) default: return fmt.Errorf("unknown doc type %q. Try 'markdown' or 'man'", o.docTypeString) } }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/list_test.go
pkg/cmd/list_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "testing" "time" chart "helm.sh/helm/v4/pkg/chart/v2" "helm.sh/helm/v4/pkg/release/common" release "helm.sh/helm/v4/pkg/release/v1" ) func TestListCmd(t *testing.T) { defaultNamespace := "default" sampleTimeSeconds := int64(1452902400) timestamp1 := time.Unix(sampleTimeSeconds+1, 0).UTC() timestamp2 := time.Unix(sampleTimeSeconds+2, 0).UTC() timestamp3 := time.Unix(sampleTimeSeconds+3, 0).UTC() timestamp4 := time.Unix(sampleTimeSeconds+4, 0).UTC() chartInfo := &chart.Chart{ Metadata: &chart.Metadata{ Name: "chickadee", Version: "1.0.0", AppVersion: "0.0.1", }, } releaseFixture := []*release.Release{ { Name: "starlord", Version: 1, Namespace: defaultNamespace, Info: &release.Info{ LastDeployed: timestamp1, Status: common.StatusSuperseded, }, Chart: chartInfo, }, { Name: "starlord", Version: 2, Namespace: defaultNamespace, Info: &release.Info{ LastDeployed: timestamp1, Status: common.StatusDeployed, }, Chart: chartInfo, }, { Name: "groot", Version: 1, Namespace: defaultNamespace, Info: &release.Info{ LastDeployed: timestamp1, Status: common.StatusUninstalled, }, Chart: chartInfo, }, { Name: "gamora", Version: 1, Namespace: defaultNamespace, Info: &release.Info{ LastDeployed: timestamp1, Status: common.StatusSuperseded, }, Chart: chartInfo, }, { Name: "rocket", Version: 1, Namespace: defaultNamespace, Info: &release.Info{ LastDeployed: timestamp2, Status: common.StatusFailed, }, Chart: chartInfo, }, { Name: "drax", Version: 1, Namespace: defaultNamespace, Info: &release.Info{ LastDeployed: timestamp1, Status: common.StatusUninstalling, }, Chart: chartInfo, }, { Name: "thanos", Version: 1, Namespace: defaultNamespace, Info: &release.Info{ LastDeployed: timestamp1, Status: common.StatusPendingInstall, }, Chart: chartInfo, }, { Name: "hummingbird", Version: 1, Namespace: defaultNamespace, Info: &release.Info{ LastDeployed: timestamp3, Status: common.StatusDeployed, }, Chart: chartInfo, }, { Name: "iguana", Version: 2, Namespace: defaultNamespace, Info: &release.Info{ LastDeployed: timestamp4, Status: common.StatusDeployed, }, Chart: chartInfo, }, { Name: "starlord", Version: 2, Namespace: "milano", Info: &release.Info{ LastDeployed: timestamp1, Status: common.StatusDeployed, }, Chart: chartInfo, }, } tests := []cmdTestCase{{ name: "list releases", cmd: "list", golden: "output/list-all.txt", rels: releaseFixture, }, { name: "list without headers", cmd: "list --no-headers", golden: "output/list-all-no-headers.txt", rels: releaseFixture, }, { name: "list releases sorted by release date", cmd: "list --date", golden: "output/list-all-date.txt", rels: releaseFixture, }, { name: "list failed releases", cmd: "list --failed", golden: "output/list-failed.txt", rels: releaseFixture, }, { name: "list filtered releases", cmd: "list --filter='.*'", golden: "output/list-all.txt", rels: releaseFixture, }, { name: "list releases, limited to one release", cmd: "list --max 1", golden: "output/list-all-max.txt", rels: releaseFixture, }, { name: "list releases, offset by one", cmd: "list --offset 1", golden: "output/list-all-offset.txt", rels: releaseFixture, }, { name: "list pending releases", cmd: "list --pending", golden: "output/list-pending.txt", rels: releaseFixture, }, { name: "list releases in reverse order", cmd: "list --reverse", golden: "output/list-all-reverse.txt", rels: releaseFixture, }, { name: "list releases sorted by reversed release date", cmd: "list --date --reverse", golden: "output/list-all-date-reversed.txt", rels: releaseFixture, }, { name: "list releases in short output format", cmd: "list --short", golden: "output/list-all-short.txt", rels: releaseFixture, }, { name: "list releases in short output format", cmd: "list --short --output yaml", golden: "output/list-all-short-yaml.txt", rels: releaseFixture, }, { name: "list releases in short output format", cmd: "list --short --output json", golden: "output/list-all-short-json.txt", rels: releaseFixture, }, { name: "list deployed and failed releases only", cmd: "list --deployed --failed", golden: "output/list.txt", rels: releaseFixture, }, { name: "list superseded releases", cmd: "list --superseded", golden: "output/list-superseded.txt", rels: releaseFixture, }, { name: "list uninstalled releases", cmd: "list --uninstalled", golden: "output/list-uninstalled.txt", rels: releaseFixture, }, { name: "list releases currently uninstalling", cmd: "list --uninstalling", golden: "output/list-uninstalling.txt", rels: releaseFixture, }, { name: "list releases in another namespace", cmd: "list -n milano", golden: "output/list-namespace.txt", rels: releaseFixture, }} runTestCmd(t, tests) } func TestListOutputCompletion(t *testing.T) { outputFlagCompletionTest(t, "list") } func TestListFileCompletion(t *testing.T) { checkFileCompletion(t, "list", false) } func TestListOutputFormats(t *testing.T) { defaultNamespace := "default" timestamp := time.Unix(1452902400, 0).UTC() chartInfo := &chart.Chart{ Metadata: &chart.Metadata{ Name: "test-chart", Version: "1.0.0", AppVersion: "0.0.1", }, } releaseFixture := []*release.Release{ { Name: "test-release", Version: 1, Namespace: defaultNamespace, Info: &release.Info{ LastDeployed: timestamp, Status: common.StatusDeployed, }, Chart: chartInfo, }, } tests := []cmdTestCase{{ name: "list releases in json format", cmd: "list --output json", golden: "output/list-json.txt", rels: releaseFixture, }, { name: "list releases in yaml format", cmd: "list --output yaml", golden: "output/list-yaml.txt", rels: releaseFixture, }} runTestCmd(t, tests) } func TestReleaseListWriter(t *testing.T) { timestamp := time.Unix(1452902400, 0).UTC() chartInfo := &chart.Chart{ Metadata: &chart.Metadata{ Name: "test-chart", Version: "1.0.0", AppVersion: "0.0.1", }, } releases := []*release.Release{ { Name: "test-release", Version: 1, Namespace: "default", Info: &release.Info{ LastDeployed: timestamp, Status: common.StatusDeployed, }, Chart: chartInfo, }, } tests := []struct { name string releases []*release.Release timeFormat string noHeaders bool noColor bool }{ { name: "empty releases list", releases: []*release.Release{}, timeFormat: "", noHeaders: false, noColor: false, }, { name: "custom time format", releases: releases, timeFormat: "2006-01-02", noHeaders: false, noColor: false, }, { name: "no headers", releases: releases, timeFormat: "", noHeaders: true, noColor: false, }, { name: "no color", releases: releases, timeFormat: "", noHeaders: false, noColor: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { writer := newReleaseListWriter(tt.releases, tt.timeFormat, tt.noHeaders, tt.noColor) if writer == nil { t.Error("Expected writer to be non-nil") } else { if len(writer.releases) != len(tt.releases) { t.Errorf("Expected %d releases, got %d", len(tt.releases), len(writer.releases)) } } }) } } func TestReleaseListWriterMethods(t *testing.T) { timestamp := time.Unix(1452902400, 0).UTC() zeroTimestamp := time.Time{} chartInfo := &chart.Chart{ Metadata: &chart.Metadata{ Name: "test-chart", Version: "1.0.0", AppVersion: "0.0.1", }, } releases := []*release.Release{ { Name: "test-release", Version: 1, Namespace: "default", Info: &release.Info{ LastDeployed: timestamp, Status: common.StatusDeployed, }, Chart: chartInfo, }, { Name: "zero-time-release", Version: 1, Namespace: "default", Info: &release.Info{ LastDeployed: zeroTimestamp, Status: common.StatusFailed, }, Chart: chartInfo, }, } tests := []struct { name string status common.Status }{ {"deployed", common.StatusDeployed}, {"failed", common.StatusFailed}, {"pending-install", common.StatusPendingInstall}, {"pending-upgrade", common.StatusPendingUpgrade}, {"pending-rollback", common.StatusPendingRollback}, {"uninstalling", common.StatusUninstalling}, {"uninstalled", common.StatusUninstalled}, {"superseded", common.StatusSuperseded}, {"unknown", common.StatusUnknown}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { testReleases := []*release.Release{ { Name: "test-release", Version: 1, Namespace: "default", Info: &release.Info{ LastDeployed: timestamp, Status: tt.status, }, Chart: chartInfo, }, } writer := newReleaseListWriter(testReleases, "", false, false) var buf []byte out := &bytesWriter{buf: &buf} err := writer.WriteJSON(out) if err != nil { t.Errorf("WriteJSON failed: %v", err) } err = writer.WriteYAML(out) if err != nil { t.Errorf("WriteYAML failed: %v", err) } err = writer.WriteTable(out) if err != nil { t.Errorf("WriteTable failed: %v", err) } }) } writer := newReleaseListWriter(releases, "", false, false) var buf []byte out := &bytesWriter{buf: &buf} err := writer.WriteJSON(out) if err != nil { t.Errorf("WriteJSON failed: %v", err) } err = writer.WriteYAML(out) if err != nil { t.Errorf("WriteYAML failed: %v", err) } err = writer.WriteTable(out) if err != nil { t.Errorf("WriteTable failed: %v", err) } } func TestFilterReleases(t *testing.T) { releases := []*release.Release{ {Name: "release1"}, {Name: "release2"}, {Name: "release3"}, } tests := []struct { name string releases []*release.Release ignoredReleaseNames []string expectedCount int }{ { name: "nil ignored list", releases: releases, ignoredReleaseNames: nil, expectedCount: 3, }, { name: "empty ignored list", releases: releases, ignoredReleaseNames: []string{}, expectedCount: 3, }, { name: "filter one release", releases: releases, ignoredReleaseNames: []string{"release1"}, expectedCount: 2, }, { name: "filter multiple releases", releases: releases, ignoredReleaseNames: []string{"release1", "release3"}, expectedCount: 1, }, { name: "filter non-existent release", releases: releases, ignoredReleaseNames: []string{"non-existent"}, expectedCount: 3, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := filterReleases(tt.releases, tt.ignoredReleaseNames) if len(result) != tt.expectedCount { t.Errorf("Expected %d releases, got %d", tt.expectedCount, len(result)) } }) } } type bytesWriter struct { buf *[]byte } func (b *bytesWriter) Write(p []byte) (n int, err error) { *b.buf = append(*b.buf, p...) return len(p), nil } func TestListCustomTimeFormat(t *testing.T) { defaultNamespace := "default" timestamp := time.Unix(1452902400, 0).UTC() chartInfo := &chart.Chart{ Metadata: &chart.Metadata{ Name: "test-chart", Version: "1.0.0", AppVersion: "0.0.1", }, } releaseFixture := []*release.Release{ { Name: "test-release", Version: 1, Namespace: defaultNamespace, Info: &release.Info{ LastDeployed: timestamp, Status: common.StatusDeployed, }, Chart: chartInfo, }, } tests := []cmdTestCase{{ name: "list releases with custom time format", cmd: "list --time-format '2006-01-02 15:04:05'", golden: "output/list-time-format.txt", rels: releaseFixture, }} runTestCmd(t, tests) } func TestListStatusMapping(t *testing.T) { defaultNamespace := "default" timestamp := time.Unix(1452902400, 0).UTC() chartInfo := &chart.Chart{ Metadata: &chart.Metadata{ Name: "test-chart", Version: "1.0.0", AppVersion: "0.0.1", }, } testCases := []struct { name string status common.Status }{ {"deployed", common.StatusDeployed}, {"failed", common.StatusFailed}, {"pending-install", common.StatusPendingInstall}, {"pending-upgrade", common.StatusPendingUpgrade}, {"pending-rollback", common.StatusPendingRollback}, {"uninstalling", common.StatusUninstalling}, {"uninstalled", common.StatusUninstalled}, {"superseded", common.StatusSuperseded}, {"unknown", common.StatusUnknown}, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { releaseFixture := []*release.Release{ { Name: "test-release", Version: 1, Namespace: defaultNamespace, Info: &release.Info{ LastDeployed: timestamp, Status: tc.status, }, Chart: chartInfo, }, } writer := newReleaseListWriter(releaseFixture, "", false, false) if len(writer.releases) != 1 { t.Errorf("Expected 1 release, got %d", len(writer.releases)) } if writer.releases[0].Status != tc.status.String() { t.Errorf("Expected status %s, got %s", tc.status.String(), writer.releases[0].Status) } }) } }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/repo_add.go
pkg/cmd/repo_add.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "context" "errors" "fmt" "io" "io/fs" "os" "path/filepath" "strings" "time" "github.com/gofrs/flock" "github.com/spf13/cobra" "golang.org/x/term" "sigs.k8s.io/yaml" "helm.sh/helm/v4/pkg/cmd/require" "helm.sh/helm/v4/pkg/getter" "helm.sh/helm/v4/pkg/repo/v1" ) // Repositories that have been permanently deleted and no longer work var deprecatedRepos = map[string]string{ "//kubernetes-charts.storage.googleapis.com": "https://charts.helm.sh/stable", "//kubernetes-charts-incubator.storage.googleapis.com": "https://charts.helm.sh/incubator", } type repoAddOptions struct { name string url string username string password string passwordFromStdinOpt bool passCredentialsAll bool forceUpdate bool allowDeprecatedRepos bool timeout time.Duration certFile string keyFile string caFile string insecureSkipTLSVerify bool repoFile string repoCache string } func newRepoAddCmd(out io.Writer) *cobra.Command { o := &repoAddOptions{} cmd := &cobra.Command{ Use: "add [NAME] [URL]", Short: "add a chart repository", Args: require.ExactArgs(2), ValidArgsFunction: func(_ *cobra.Command, args []string, _ string) ([]string, cobra.ShellCompDirective) { if len(args) > 1 { return noMoreArgsComp() } return nil, cobra.ShellCompDirectiveNoFileComp }, RunE: func(_ *cobra.Command, args []string) error { o.name = args[0] o.url = args[1] o.repoFile = settings.RepositoryConfig o.repoCache = settings.RepositoryCache return o.run(out) }, } f := cmd.Flags() f.StringVar(&o.username, "username", "", "chart repository username") f.StringVar(&o.password, "password", "", "chart repository password") f.BoolVarP(&o.passwordFromStdinOpt, "password-stdin", "", false, "read chart repository password from stdin") f.BoolVar(&o.forceUpdate, "force-update", false, "replace (overwrite) the repo if it already exists") 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.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.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.DurationVar(&o.timeout, "timeout", getter.DefaultHTTPTimeout*time.Second, "time to wait for the index file download to complete") return cmd } func (o *repoAddOptions) run(out io.Writer) error { // Block deprecated repos if !o.allowDeprecatedRepos { for oldURL, newURL := range deprecatedRepos { if strings.Contains(o.url, oldURL) { return fmt.Errorf("repo %q is no longer available; try %q instead", o.url, newURL) } } } // Ensure the file directory exists as it is required for file locking err := os.MkdirAll(filepath.Dir(o.repoFile), os.ModePerm) if err != nil && !os.IsExist(err) { return err } // Acquire a file lock for process synchronization repoFileExt := filepath.Ext(o.repoFile) var lockPath string if len(repoFileExt) > 0 && len(repoFileExt) < len(o.repoFile) { lockPath = strings.TrimSuffix(o.repoFile, repoFileExt) + ".lock" } else { lockPath = o.repoFile + ".lock" } fileLock := flock.New(lockPath) lockCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() locked, err := fileLock.TryLockContext(lockCtx, time.Second) if err == nil && locked { defer fileLock.Unlock() } if err != nil { return err } b, err := os.ReadFile(o.repoFile) if err != nil && !errors.Is(err, fs.ErrNotExist) { return err } var f repo.File if err := yaml.Unmarshal(b, &f); err != nil { return err } if o.username != "" && o.password == "" { if o.passwordFromStdinOpt { passwordFromStdin, err := io.ReadAll(os.Stdin) if err != nil { return err } password := strings.TrimSuffix(string(passwordFromStdin), "\n") password = strings.TrimSuffix(password, "\r") o.password = password } else { fd := int(os.Stdin.Fd()) fmt.Fprint(out, "Password: ") password, err := term.ReadPassword(fd) fmt.Fprintln(out) if err != nil { return err } o.password = string(password) } } c := repo.Entry{ Name: o.name, URL: o.url, Username: o.username, Password: o.password, PassCredentialsAll: o.passCredentialsAll, CertFile: o.certFile, KeyFile: o.keyFile, CAFile: o.caFile, InsecureSkipTLSVerify: o.insecureSkipTLSVerify, } // Check if the repo name is legal if strings.Contains(o.name, "/") { return fmt.Errorf("repository name (%s) contains '/', please specify a different name without '/'", o.name) } // If the repo exists do one of two things: // 1. If the configuration for the name is the same continue without error // 2. When the config is different require --force-update if !o.forceUpdate && f.Has(o.name) { existing := f.Get(o.name) if c != *existing { // The input coming in for the name is different from what is already // configured. Return an error. return fmt.Errorf("repository name (%s) already exists, please specify a different name", o.name) } // The add is idempotent so do nothing fmt.Fprintf(out, "%q already exists with the same configuration, skipping\n", o.name) return nil } r, err := repo.NewChartRepository(&c, getter.All(settings, getter.WithTimeout(o.timeout))) if err != nil { return err } if o.repoCache != "" { r.CachePath = o.repoCache } if _, err := r.DownloadIndexFile(); err != nil { return fmt.Errorf("looks like %q is not a valid chart repository or cannot be reached: %w", o.url, err) } f.Update(&c) if err := f.WriteFile(o.repoFile, 0o600); err != nil { return err } fmt.Fprintf(out, "%q has been added to your repositories\n", o.name) return nil }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/list.go
pkg/cmd/list.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "io" "os" "slices" "strconv" "github.com/gosuri/uitable" "github.com/spf13/cobra" coloroutput "helm.sh/helm/v4/internal/cli/output" "helm.sh/helm/v4/pkg/action" "helm.sh/helm/v4/pkg/cli/output" "helm.sh/helm/v4/pkg/cmd/require" "helm.sh/helm/v4/pkg/release/common" release "helm.sh/helm/v4/pkg/release/v1" ) var listHelp = ` This command lists all of the releases for a specified namespace (uses current namespace context if namespace not specified). By default, it lists all releases in any status. Individual status filters like '--deployed', '--failed', '--pending', '--uninstalled', '--superseded', and '--uninstalling' can be used to show only releases in specific states. Such flags can be combined: '--deployed --failed'. By default, items are sorted alphabetically. Use the '-d' flag to sort by release date. If the --filter flag is provided, it will be treated as a filter. Filters are regular expressions (Perl compatible) that are applied to the list of releases. Only items that match the filter will be returned. $ helm list --filter 'ara[a-z]+' NAME UPDATED CHART maudlin-arachnid 2020-06-18 14:17:46.125134977 +0000 UTC alpine-0.1.0 If no results are found, 'helm list' will exit 0, but with no output (or in the case of no '-q' flag, only headers). By default, up to 256 items may be returned. To limit this, use the '--max' flag. Setting '--max' to 0 will not return all results. Rather, it will return the server's default, which may be much higher than 256. Pairing the '--max' flag with the '--offset' flag allows you to page through results. ` func newListCmd(cfg *action.Configuration, out io.Writer) *cobra.Command { client := action.NewList(cfg) var outfmt output.Format cmd := &cobra.Command{ Use: "list", Short: "list releases", Long: listHelp, Aliases: []string{"ls"}, Args: require.NoArgs, ValidArgsFunction: noMoreArgsCompFunc, RunE: func(cmd *cobra.Command, _ []string) error { if client.AllNamespaces { if err := cfg.Init(settings.RESTClientGetter(), "", os.Getenv("HELM_DRIVER")); err != nil { return err } } client.SetStateMask() resultsi, err := client.Run() if err != nil { return err } results, err := releaseListToV1List(resultsi) if err != nil { return err } if client.Short { names := make([]string, 0, len(results)) for _, res := range results { names = append(names, res.Name) } outputFlag := cmd.Flag("output") switch outputFlag.Value.String() { case "json": output.EncodeJSON(out, names) return nil case "yaml": output.EncodeYAML(out, names) return nil case "table": for _, res := range results { fmt.Fprintln(out, res.Name) } return nil } } return outfmt.Write(out, newReleaseListWriter(results, client.TimeFormat, client.NoHeaders, settings.ShouldDisableColor())) }, } f := cmd.Flags() f.BoolVarP(&client.Short, "short", "q", false, "output short (quiet) listing format") f.BoolVarP(&client.NoHeaders, "no-headers", "", false, "don't print headers when using the default output format") f.StringVar(&client.TimeFormat, "time-format", "", `format time using golang time formatter. Example: --time-format "2006-01-02 15:04:05Z0700"`) f.BoolVarP(&client.ByDate, "date", "d", false, "sort by release date") f.BoolVarP(&client.SortReverse, "reverse", "r", false, "reverse the sort order") f.BoolVar(&client.Uninstalled, "uninstalled", false, "show uninstalled releases (if 'helm uninstall --keep-history' was used)") f.BoolVar(&client.Superseded, "superseded", false, "show superseded releases") f.BoolVar(&client.Uninstalling, "uninstalling", false, "show releases that are currently being uninstalled") f.BoolVar(&client.Deployed, "deployed", false, "show deployed releases") f.BoolVar(&client.Failed, "failed", false, "show failed releases") f.BoolVar(&client.Pending, "pending", false, "show pending releases") f.BoolVarP(&client.AllNamespaces, "all-namespaces", "A", false, "list releases across all namespaces") f.IntVarP(&client.Limit, "max", "m", 256, "maximum number of releases to fetch") 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.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) return cmd } type releaseElement struct { Name string `json:"name"` Namespace string `json:"namespace"` Revision string `json:"revision"` Updated string `json:"updated"` Status string `json:"status"` Chart string `json:"chart"` AppVersion string `json:"app_version"` } type releaseListWriter struct { releases []releaseElement noHeaders bool noColor bool } func newReleaseListWriter(releases []*release.Release, timeFormat string, noHeaders bool, noColor bool) *releaseListWriter { // Initialize the array so no results returns an empty array instead of null elements := make([]releaseElement, 0, len(releases)) for _, r := range releases { element := releaseElement{ Name: r.Name, Namespace: r.Namespace, Revision: strconv.Itoa(r.Version), Status: r.Info.Status.String(), Chart: formatChartName(r.Chart), AppVersion: formatAppVersion(r.Chart), } t := "-" if tspb := r.Info.LastDeployed; !tspb.IsZero() { if timeFormat != "" { t = tspb.Format(timeFormat) } else { t = tspb.String() } } element.Updated = t elements = append(elements, element) } return &releaseListWriter{elements, noHeaders, noColor} } func (w *releaseListWriter) WriteTable(out io.Writer) error { table := uitable.New() if !w.noHeaders { table.AddRow( coloroutput.ColorizeHeader("NAME", w.noColor), coloroutput.ColorizeHeader("NAMESPACE", w.noColor), coloroutput.ColorizeHeader("REVISION", w.noColor), coloroutput.ColorizeHeader("UPDATED", w.noColor), coloroutput.ColorizeHeader("STATUS", w.noColor), coloroutput.ColorizeHeader("CHART", w.noColor), coloroutput.ColorizeHeader("APP VERSION", w.noColor), ) } for _, r := range w.releases { // Parse the status string back to a release.Status to use color var status common.Status switch r.Status { case "deployed": status = common.StatusDeployed case "failed": status = common.StatusFailed case "pending-install": status = common.StatusPendingInstall case "pending-upgrade": status = common.StatusPendingUpgrade case "pending-rollback": status = common.StatusPendingRollback case "uninstalling": status = common.StatusUninstalling case "uninstalled": status = common.StatusUninstalled case "superseded": status = common.StatusSuperseded case "unknown": status = common.StatusUnknown default: status = common.Status(r.Status) } table.AddRow(r.Name, coloroutput.ColorizeNamespace(r.Namespace, w.noColor), r.Revision, r.Updated, coloroutput.ColorizeStatus(status, w.noColor), r.Chart, r.AppVersion) } return output.EncodeTable(out, table) } func (w *releaseListWriter) WriteJSON(out io.Writer) error { return output.EncodeJSON(out, w.releases) } func (w *releaseListWriter) WriteYAML(out io.Writer) error { return output.EncodeYAML(out, w.releases) } // Returns all releases from 'releases', except those with names matching 'ignoredReleases' func filterReleases(releases []*release.Release, ignoredReleaseNames []string) []*release.Release { // if ignoredReleaseNames is nil, just return releases if ignoredReleaseNames == nil { return releases } var filteredReleases []*release.Release for _, rel := range releases { found := slices.Contains(ignoredReleaseNames, rel.Name) if !found { filteredReleases = append(filteredReleases, rel) } } return filteredReleases } // Provide dynamic auto-completion for release names func compListReleases(toComplete string, ignoredReleaseNames []string, cfg *action.Configuration) ([]string, cobra.ShellCompDirective) { cobra.CompDebugln(fmt.Sprintf("compListReleases with toComplete %s", toComplete), settings.Debug) client := action.NewList(cfg) client.All = true client.Limit = 0 // Do not filter so as to get the entire list of releases. // This will allow zsh and fish to match completion choices // on other criteria then prefix. For example: // helm status ingress<TAB> // can match // helm status nginx-ingress // // client.Filter = fmt.Sprintf("^%s", toComplete) client.SetStateMask() releasesi, err := client.Run() if err != nil { return nil, cobra.ShellCompDirectiveDefault } releases, err := releaseListToV1List(releasesi) if err != nil { return nil, cobra.ShellCompDirectiveDefault } var choices []string filteredReleases := filterReleases(releases, ignoredReleaseNames) for _, rel := range filteredReleases { choices = append(choices, fmt.Sprintf("%s\t%s-%s -> %s", rel.Name, rel.Chart.Metadata.Name, rel.Chart.Metadata.Version, rel.Info.Status.String())) } return choices, cobra.ShellCompDirectiveNoFileComp }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/registry_login_test.go
pkg/cmd/registry_login_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "testing" ) func TestRegistryLoginFileCompletion(t *testing.T) { checkFileCompletion(t, "registry login", false) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/plugin_list.go
pkg/cmd/plugin_list.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "io" "log/slog" "path/filepath" "slices" "github.com/gosuri/uitable" "github.com/spf13/cobra" "helm.sh/helm/v4/internal/plugin" "helm.sh/helm/v4/internal/plugin/schema" ) func newPluginListCmd(out io.Writer) *cobra.Command { var pluginType string cmd := &cobra.Command{ Use: "list", Aliases: []string{"ls"}, Short: "list installed Helm plugins", ValidArgsFunction: noMoreArgsCompFunc, RunE: func(_ *cobra.Command, _ []string) error { slog.Debug("pluginDirs", "directory", settings.PluginsDirectory) dirs := filepath.SplitList(settings.PluginsDirectory) descriptor := plugin.Descriptor{ Type: pluginType, } plugins, err := plugin.FindPlugins(dirs, descriptor) if err != nil { return err } // Get signing info for all plugins signingInfo := plugin.GetSigningInfoForPlugins(plugins) table := uitable.New() table.AddRow("NAME", "VERSION", "TYPE", "APIVERSION", "PROVENANCE", "SOURCE") for _, p := range plugins { m := p.Metadata() sourceURL := m.SourceURL if sourceURL == "" { sourceURL = "unknown" } // Get signing status signedStatus := "unknown" if info, ok := signingInfo[m.Name]; ok { signedStatus = info.Status } table.AddRow(m.Name, m.Version, m.Type, m.APIVersion, signedStatus, sourceURL) } fmt.Fprintln(out, table) return nil }, } f := cmd.Flags() f.StringVar(&pluginType, "type", "", "Plugin type") return cmd } // Returns all plugins from plugins, except those with names matching ignoredPluginNames func filterPlugins(plugins []plugin.Plugin, ignoredPluginNames []string) []plugin.Plugin { // if ignoredPluginNames is nil or empty, just return plugins if len(ignoredPluginNames) == 0 { return plugins } var filteredPlugins []plugin.Plugin for _, plugin := range plugins { found := slices.Contains(ignoredPluginNames, plugin.Metadata().Name) if !found { filteredPlugins = append(filteredPlugins, plugin) } } return filteredPlugins } // Provide dynamic auto-completion for plugin names func compListPlugins(_ string, ignoredPluginNames []string) []string { var pNames []string dirs := filepath.SplitList(settings.PluginsDirectory) descriptor := plugin.Descriptor{ Type: "cli/v1", } plugins, err := plugin.FindPlugins(dirs, descriptor) if err == nil && len(plugins) > 0 { filteredPlugins := filterPlugins(plugins, ignoredPluginNames) for _, p := range filteredPlugins { m := p.Metadata() var shortHelp string if config, ok := m.Config.(*schema.ConfigCLIV1); ok { shortHelp = config.ShortHelp } pNames = append(pNames, fmt.Sprintf("%s\t%s", p.Metadata().Name, shortHelp)) } } return pNames }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/repo_list_test.go
pkg/cmd/repo_list_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "path/filepath" "testing" ) func TestRepoListOutputCompletion(t *testing.T) { outputFlagCompletionTest(t, "repo list") } func TestRepoListFileCompletion(t *testing.T) { checkFileCompletion(t, "repo list", false) } func TestRepoList(t *testing.T) { rootDir := t.TempDir() repoFile := filepath.Join(rootDir, "repositories.yaml") repoFile2 := "testdata/repositories.yaml" tests := []cmdTestCase{ { name: "list with no repos", cmd: fmt.Sprintf("repo list --repository-config %s --repository-cache %s", repoFile, rootDir), golden: "output/repo-list-empty.txt", wantError: false, }, { name: "list with repos", cmd: fmt.Sprintf("repo list --repository-config %s --repository-cache %s", repoFile2, rootDir), golden: "output/repo-list.txt", wantError: false, }, { name: "list without headers", cmd: fmt.Sprintf("repo list --repository-config %s --repository-cache %s --no-headers", repoFile2, rootDir), golden: "output/repo-list-no-headers.txt", wantError: false, }, } runTestCmd(t, tests) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/repo.go
pkg/cmd/repo.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "errors" "io" "io/fs" "github.com/spf13/cobra" "helm.sh/helm/v4/pkg/cmd/require" ) var repoHelm = ` This command consists of multiple subcommands to interact with chart repositories. It can be used to add, remove, list, and index chart repositories. ` func newRepoCmd(out io.Writer) *cobra.Command { cmd := &cobra.Command{ Use: "repo add|remove|list|index|update [ARGS]", Short: "add, list, remove, update, and index chart repositories", Long: repoHelm, Args: require.NoArgs, } cmd.AddCommand(newRepoAddCmd(out)) cmd.AddCommand(newRepoListCmd(out)) cmd.AddCommand(newRepoRemoveCmd(out)) cmd.AddCommand(newRepoIndexCmd(out)) cmd.AddCommand(newRepoUpdateCmd(out)) return cmd } func isNotExist(err error) bool { return errors.Is(err, fs.ErrNotExist) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/version_test.go
pkg/cmd/version_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "testing" ) func TestVersion(t *testing.T) { tests := []cmdTestCase{{ name: "default", cmd: "version", golden: "output/version.txt", }, { name: "short", cmd: "version --short", golden: "output/version-short.txt", }, { name: "template", cmd: "version --template='Version: {{.Version}}'", golden: "output/version-template.txt", }} runTestCmd(t, tests) } func TestVersionFileCompletion(t *testing.T) { checkFileCompletion(t, "version", false) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/get_values_test.go
pkg/cmd/get_values_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "testing" release "helm.sh/helm/v4/pkg/release/v1" ) func TestGetValuesCmd(t *testing.T) { tests := []cmdTestCase{{ name: "get values with a release", cmd: "get values thomas-guide", golden: "output/get-values.txt", rels: []*release.Release{release.Mock(&release.MockReleaseOptions{Name: "thomas-guide"})}, }, { name: "get values requires release name arg", cmd: "get values", golden: "output/get-values-args.txt", rels: []*release.Release{release.Mock(&release.MockReleaseOptions{Name: "thomas-guide"})}, wantError: true, }, { name: "get values thomas-guide (all)", cmd: "get values thomas-guide --all", golden: "output/get-values-all.txt", rels: []*release.Release{release.Mock(&release.MockReleaseOptions{Name: "thomas-guide"})}, }, { name: "get values to json", cmd: "get values thomas-guide --output json", golden: "output/values.json", rels: []*release.Release{release.Mock(&release.MockReleaseOptions{Name: "thomas-guide"})}, }, { name: "get values to yaml", cmd: "get values thomas-guide --output yaml", golden: "output/values.yaml", rels: []*release.Release{release.Mock(&release.MockReleaseOptions{Name: "thomas-guide"})}, }} runTestCmd(t, tests) } func TestGetValuesCompletion(t *testing.T) { checkReleaseCompletion(t, "get values", false) } func TestGetValuesRevisionCompletion(t *testing.T) { revisionFlagCompletionTest(t, "get values") } func TestGetValuesOutputCompletion(t *testing.T) { outputFlagCompletionTest(t, "get values") } func TestGetValuesFileCompletion(t *testing.T) { checkFileCompletion(t, "get values", false) checkFileCompletion(t, "get values myrelease", false) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/lint.go
pkg/cmd/lint.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "errors" "fmt" "io" "os" "path/filepath" "strings" "github.com/spf13/cobra" "helm.sh/helm/v4/pkg/action" "helm.sh/helm/v4/pkg/chart/common" "helm.sh/helm/v4/pkg/chart/v2/lint/support" "helm.sh/helm/v4/pkg/cli/values" "helm.sh/helm/v4/pkg/cmd/require" "helm.sh/helm/v4/pkg/getter" ) var longLintHelp = ` This command takes a path to a chart and runs a series of tests to verify that the chart is well-formed. If the linter encounters things that will cause the chart to fail installation, it will emit [ERROR] messages. If it encounters issues that break with convention or recommendation, it will emit [WARNING] messages. ` func newLintCmd(out io.Writer) *cobra.Command { client := action.NewLint() valueOpts := &values.Options{} var kubeVersion string cmd := &cobra.Command{ Use: "lint PATH", Short: "examine a chart for possible issues", Long: longLintHelp, Args: require.MinimumNArgs(1), RunE: func(_ *cobra.Command, args []string) error { paths := args if kubeVersion != "" { parsedKubeVersion, err := common.ParseKubeVersion(kubeVersion) if err != nil { return fmt.Errorf("invalid kube version '%s': %s", kubeVersion, err) } client.KubeVersion = parsedKubeVersion } if client.WithSubcharts { for _, p := range paths { filepath.Walk(filepath.Join(p, "charts"), func(path string, info os.FileInfo, _ error) error { if info != nil { if info.Name() == "Chart.yaml" { paths = append(paths, filepath.Dir(path)) } else if strings.HasSuffix(path, ".tgz") || strings.HasSuffix(path, ".tar.gz") { paths = append(paths, path) } } return nil }) } } client.Namespace = settings.Namespace() vals, err := valueOpts.MergeValues(getter.All(settings)) if err != nil { return err } var message strings.Builder failed := 0 errorsOrWarnings := 0 for _, path := range paths { result := client.Run([]string{path}, vals) // If there is no errors/warnings and quiet flag is set // go to the next chart hasWarningsOrErrors := action.HasWarningsOrErrors(result) if hasWarningsOrErrors { errorsOrWarnings++ } if client.Quiet && !hasWarningsOrErrors { continue } fmt.Fprintf(&message, "==> Linting %s\n", path) // All the Errors that are generated by a chart // that failed a lint will be included in the // results.Messages so we only need to print // the Errors if there are no Messages. if len(result.Messages) == 0 { for _, err := range result.Errors { fmt.Fprintf(&message, "Error %s\n", err) } } for _, msg := range result.Messages { if !client.Quiet || msg.Severity > support.InfoSev { fmt.Fprintf(&message, "%s\n", msg) } } if len(result.Errors) != 0 { failed++ } // Adding extra new line here to break up the // results, stops this from being a big wall of // text and makes it easier to follow. fmt.Fprint(&message, "\n") } fmt.Fprint(out, message.String()) summary := fmt.Sprintf("%d chart(s) linted, %d chart(s) failed", len(paths), failed) if failed > 0 { return errors.New(summary) } if !client.Quiet || errorsOrWarnings > 0 { fmt.Fprintln(out, summary) } return nil }, } f := cmd.Flags() f.BoolVar(&client.Strict, "strict", false, "fail on lint warnings") f.BoolVar(&client.WithSubcharts, "with-subcharts", false, "lint dependent charts") f.BoolVar(&client.Quiet, "quiet", false, "print only warnings and errors") f.BoolVar(&client.SkipSchemaValidation, "skip-schema-validation", false, "if set, disables JSON schema validation") f.StringVar(&kubeVersion, "kube-version", "", "Kubernetes version used for capabilities and deprecation checks") addValueOptionsFlags(f, valueOpts) return cmd }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/repo_list.go
pkg/cmd/repo_list.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "io" "github.com/gosuri/uitable" "github.com/spf13/cobra" "helm.sh/helm/v4/pkg/cli/output" "helm.sh/helm/v4/pkg/cmd/require" "helm.sh/helm/v4/pkg/repo/v1" ) func newRepoListCmd(out io.Writer) *cobra.Command { var outfmt output.Format var noHeaders bool cmd := &cobra.Command{ Use: "list", Aliases: []string{"ls"}, Short: "list chart repositories", Args: require.NoArgs, ValidArgsFunction: noMoreArgsCompFunc, RunE: func(cmd *cobra.Command, _ []string) error { // The error is silently ignored. If no repository file exists, it cannot be loaded, // or the file isn't the right format to be parsed the error is ignored. The // repositories will be 0. f, _ := repo.LoadFile(settings.RepositoryConfig) if len(f.Repositories) == 0 && outfmt != output.JSON && outfmt != output.YAML { fmt.Fprintln(cmd.ErrOrStderr(), "no repositories to show") return nil } w := &repoListWriter{ repos: f.Repositories, noHeaders: noHeaders, } return outfmt.Write(out, w) }, } cmd.Flags().BoolVar(&noHeaders, "no-headers", false, "suppress headers in the output") bindOutputFlag(cmd, &outfmt) return cmd } type repositoryElement struct { Name string `json:"name"` URL string `json:"url"` } type repoListWriter struct { repos []*repo.Entry noHeaders bool } func (r *repoListWriter) WriteTable(out io.Writer) error { table := uitable.New() if !r.noHeaders { table.AddRow("NAME", "URL") } for _, re := range r.repos { table.AddRow(re.Name, re.URL) } return output.EncodeTable(out, table) } func (r *repoListWriter) WriteJSON(out io.Writer) error { return r.encodeByFormat(out, output.JSON) } func (r *repoListWriter) WriteYAML(out io.Writer) error { return r.encodeByFormat(out, output.YAML) } func (r *repoListWriter) encodeByFormat(out io.Writer, format output.Format) error { // Initialize the array so no results returns an empty array instead of null repolist := make([]repositoryElement, 0, len(r.repos)) for _, re := range r.repos { repolist = append(repolist, repositoryElement{Name: re.Name, URL: re.URL}) } switch format { case output.JSON: return output.EncodeJSON(out, repolist) case output.YAML: return output.EncodeYAML(out, repolist) default: // Because this is a non-exported function and only called internally by // WriteJSON and WriteYAML, we shouldn't get invalid types return nil } } // Returns all repos from repos, except those with names matching ignoredRepoNames // Inspired by https://stackoverflow.com/a/28701031/893211 func filterRepos(repos []*repo.Entry, ignoredRepoNames []string) []*repo.Entry { // if ignoredRepoNames is nil, just return repo if ignoredRepoNames == nil { return repos } filteredRepos := make([]*repo.Entry, 0) ignored := make(map[string]bool, len(ignoredRepoNames)) for _, repoName := range ignoredRepoNames { ignored[repoName] = true } for _, repo := range repos { if _, removed := ignored[repo.Name]; !removed { filteredRepos = append(filteredRepos, repo) } } return filteredRepos } // Provide dynamic auto-completion for repo names func compListRepos(_ string, ignoredRepoNames []string) []string { var rNames []string f, err := repo.LoadFile(settings.RepositoryConfig) if err == nil && len(f.Repositories) > 0 { filteredRepos := filterRepos(f.Repositories, ignoredRepoNames) for _, repo := range filteredRepos { rNames = append(rNames, fmt.Sprintf("%s\t%s", repo.Name, repo.URL)) } } return rNames }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/load_plugins.go
pkg/cmd/load_plugins.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "bytes" "context" "fmt" "io" "log/slog" "os" "path/filepath" "slices" "strconv" "strings" "helm.sh/helm/v4/internal/plugin/schema" "github.com/spf13/cobra" "sigs.k8s.io/yaml" "helm.sh/helm/v4/internal/plugin" ) // TODO: move pluginDynamicCompletionExecutable pkg/plugin/runtime_subprocess.go // any references to executables should be for [plugin.SubprocessPluginRuntime] only // this should also be for backwards compatibility in [plugin.Legacy] only // // TODO: for v1 make this configurable with a new CompletionCommand field for // [plugin.RuntimeConfigSubprocess] const ( pluginStaticCompletionFile = "completion.yaml" pluginDynamicCompletionExecutable = "plugin.complete" ) // loadCLIPlugins loads CLI plugins into the command list. // // This follows a different pattern than the other commands because it has // to inspect its environment and then add commands to the base command // as it finds them. func loadCLIPlugins(baseCmd *cobra.Command, out io.Writer) { // If HELM_NO_PLUGINS is set to 1, do not load plugins. if os.Getenv("HELM_NO_PLUGINS") == "1" { return } dirs := filepath.SplitList(settings.PluginsDirectory) descriptor := plugin.Descriptor{ Type: "cli/v1", } found, err := plugin.FindPlugins(dirs, descriptor) if err != nil { slog.Error("failed to load plugins", slog.String("error", err.Error())) return } // Now we create commands for all of these. for _, plug := range found { var use, short, long string var ignoreFlags bool if cliConfig, ok := plug.Metadata().Config.(*schema.ConfigCLIV1); ok { use = cliConfig.Usage short = cliConfig.ShortHelp long = cliConfig.LongHelp ignoreFlags = cliConfig.IgnoreFlags } // Set defaults if use == "" { use = plug.Metadata().Name } if short == "" { short = fmt.Sprintf("the %q plugin", plug.Metadata().Name) } // long has no default, empty is ok c := &cobra.Command{ Use: use, Short: short, Long: long, RunE: func(cmd *cobra.Command, args []string) error { u, err := processParent(cmd, args) if err != nil { return err } // For CLI plugin types runtime, set extra args and settings extraArgs := []string{} if !ignoreFlags { extraArgs = u } // Prepare environment env := os.Environ() for k, v := range settings.EnvVars() { env = append(env, fmt.Sprintf("%s=%s", k, v)) } // Invoke plugin input := &plugin.Input{ Message: schema.InputMessageCLIV1{ ExtraArgs: extraArgs, }, Env: env, Stdin: os.Stdin, Stdout: out, Stderr: os.Stderr, } _, err = plug.Invoke(context.Background(), input) if execErr, ok := err.(*plugin.InvokeExecError); ok { return CommandError{ error: execErr.Err, ExitCode: execErr.ExitCode, } } return err }, // This passes all the flags to the subcommand. DisableFlagParsing: true, } // TODO: Make sure a command with this name does not already exist. baseCmd.AddCommand(c) // For completion, we try to load more details about the plugins so as to allow for command and // flag completion of the plugin itself. // We only do this when necessary (for the "completion" and "__complete" commands) to avoid the // risk of a rogue plugin affecting Helm's normal behavior. subCmd, _, err := baseCmd.Find(os.Args[1:]) if (err == nil && ((subCmd.HasParent() && subCmd.Parent().Name() == "completion") || subCmd.Name() == cobra.ShellCompRequestCmd)) || /* for the tests */ subCmd == baseCmd.Root() { loadCompletionForPlugin(c, plug) } } } func processParent(cmd *cobra.Command, args []string) ([]string, error) { k, u := manuallyProcessArgs(args) if err := cmd.Parent().ParseFlags(k); err != nil { return nil, err } return u, nil } // manuallyProcessArgs processes an arg array, removing special args. // // Returns two sets of args: known and unknown (in that order) func manuallyProcessArgs(args []string) ([]string, []string) { known := []string{} unknown := []string{} kvargs := []string{"--kube-context", "--namespace", "-n", "--kubeconfig", "--kube-apiserver", "--kube-token", "--kube-as-user", "--kube-as-group", "--kube-ca-file", "--registry-config", "--repository-cache", "--repository-config", "--kube-insecure-skip-tls-verify", "--kube-tls-server-name"} knownArg := func(a string) bool { for _, pre := range kvargs { if strings.HasPrefix(a, pre+"=") { return true } } return false } isKnown := func(v string) string { if slices.Contains(kvargs, v) { return v } return "" } for i := 0; i < len(args); i++ { switch a := args[i]; a { case "--debug": known = append(known, a) case isKnown(a): known = append(known, a) i++ if i < len(args) { known = append(known, args[i]) } default: if knownArg(a) { known = append(known, a) continue } unknown = append(unknown, a) } } return known, unknown } // pluginCommand represents the optional completion.yaml file of a plugin type pluginCommand struct { Name string `json:"name"` ValidArgs []string `json:"validArgs"` Flags []string `json:"flags"` Commands []pluginCommand `json:"commands"` } // loadCompletionForPlugin will load and parse any completion.yaml provided by the plugin // and add the dynamic completion hook to call the optional plugin.complete func loadCompletionForPlugin(pluginCmd *cobra.Command, plug plugin.Plugin) { // Parse the yaml file providing the plugin's sub-commands and flags cmds, err := loadFile(strings.Join( []string{plug.Dir(), pluginStaticCompletionFile}, string(filepath.Separator))) if err != nil { // The file could be missing or invalid. No static completion for this plugin. slog.Debug("plugin completion file loading", slog.String("error", err.Error())) // Continue to setup dynamic completion. cmds = &pluginCommand{} } // Preserve the Usage string specified for the plugin cmds.Name = pluginCmd.Use addPluginCommands(plug, pluginCmd, cmds) } // addPluginCommands is a recursive method that adds each different level // of sub-commands and flags for the plugins that have provided such information func addPluginCommands(plug plugin.Plugin, baseCmd *cobra.Command, cmds *pluginCommand) { if cmds == nil { return } if len(cmds.Name) == 0 { slog.Debug("sub-command name field missing", slog.String("commandPath", baseCmd.CommandPath())) return } baseCmd.Use = cmds.Name baseCmd.ValidArgs = cmds.ValidArgs // Setup the same dynamic completion for each plugin sub-command. // This is because if dynamic completion is triggered, there is a single executable // to call (plugin.complete), so every sub-commands calls it in the same fashion. if cmds.Commands == nil { // Only setup dynamic completion if there are no sub-commands. This avoids // calling plugin.complete at every completion, which greatly simplifies // development of plugin.complete for plugin developers. baseCmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return pluginDynamicComp(plug, cmd, args, toComplete) } } // Create fake flags. if len(cmds.Flags) > 0 { // The flags can be created with any type, since we only need them for completion. // pflag does not allow to create short flags without a corresponding long form // so we look for all short flags and match them to any long flag. This will allow // plugins to provide short flags without a long form. // If there are more short-flags than long ones, we'll create an extra long flag with // the same single letter as the short form. shorts := []string{} longs := []string{} for _, flag := range cmds.Flags { if len(flag) == 1 { shorts = append(shorts, flag) } else { longs = append(longs, flag) } } f := baseCmd.Flags() if len(longs) >= len(shorts) { for i := range longs { if i < len(shorts) { f.BoolP(longs[i], shorts[i], false, "") } else { f.Bool(longs[i], false, "") } } } else { for i := range shorts { if i < len(longs) { f.BoolP(longs[i], shorts[i], false, "") } else { // Create a long flag with the same name as the short flag. // Not a perfect solution, but it's better than ignoring the extra short flags. f.BoolP(shorts[i], shorts[i], false, "") } } } } // Recursively add any sub-commands for _, cmd := range cmds.Commands { // Create a fake command so that completion can be done for the sub-commands of the plugin subCmd := &cobra.Command{ // This prevents Cobra from removing the flags. We want to keep the flags to pass them // to the dynamic completion script of the plugin. DisableFlagParsing: true, // A Run is required for it to be a valid command without subcommands Run: func(_ *cobra.Command, _ []string) {}, } baseCmd.AddCommand(subCmd) addPluginCommands(plug, subCmd, &cmd) } } // loadFile takes a yaml file at the given path, parses it and returns a pluginCommand object func loadFile(path string) (*pluginCommand, error) { cmds := new(pluginCommand) b, err := os.ReadFile(path) if err != nil { return cmds, fmt.Errorf("file (%s) not provided by plugin. No plugin auto-completion possible", path) } err = yaml.Unmarshal(b, cmds) return cmds, err } // pluginDynamicComp call the plugin.complete script of the plugin (if available) // to obtain the dynamic completion choices. It must pass all the flags and sub-commands // specified in the command-line to the plugin.complete executable (except helm's global flags) func pluginDynamicComp(plug plugin.Plugin, cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { subprocessPlug, ok := plug.(*plugin.SubprocessPluginRuntime) if !ok { // Completion only supported for subprocess plugins (TODO: fix this) cobra.CompDebugln(fmt.Sprintf("Unsupported plugin runtime: %q", plug.Metadata().Runtime), settings.Debug) return nil, cobra.ShellCompDirectiveDefault } var ignoreFlags bool if cliConfig, ok := subprocessPlug.Metadata().Config.(*schema.ConfigCLIV1); ok { ignoreFlags = cliConfig.IgnoreFlags } u, err := processParent(cmd, args) if err != nil { return nil, cobra.ShellCompDirectiveError } // We will call the dynamic completion script of the plugin main := strings.Join([]string{plug.Dir(), pluginDynamicCompletionExecutable}, string(filepath.Separator)) // We must include all sub-commands passed on the command-line. // To do that, we pass-in the entire CommandPath, except the first two elements // which are 'helm' and 'pluginName'. argv := strings.Split(cmd.CommandPath(), " ")[2:] if !ignoreFlags { argv = append(argv, u...) argv = append(argv, toComplete) } cobra.CompDebugln(fmt.Sprintf("calling %s with args %v", main, argv), settings.Debug) buf := new(bytes.Buffer) // Prepare environment env := os.Environ() for k, v := range settings.EnvVars() { env = append(env, fmt.Sprintf("%s=%s", k, v)) } // For subprocess runtime, use InvokeWithEnv for dynamic completion if err := subprocessPlug.InvokeWithEnv(main, argv, env, nil, buf, buf); err != nil { // The dynamic completion file is optional for a plugin, so this error is ok. cobra.CompDebugln(fmt.Sprintf("Unable to call %s: %v", main, err.Error()), settings.Debug) return nil, cobra.ShellCompDirectiveDefault } var completions []string for comp := range strings.SplitSeq(buf.String(), "\n") { // Remove any empty lines if len(comp) > 0 { completions = append(completions, comp) } } // Check if the last line of output is of the form :<integer>, which // indicates the BashCompletionDirective. directive := cobra.ShellCompDirectiveDefault if len(completions) > 0 { lastLine := completions[len(completions)-1] if len(lastLine) > 1 && lastLine[0] == ':' { if strInt, err := strconv.Atoi(lastLine[1:]); err == nil { directive = cobra.ShellCompDirective(strInt) completions = completions[:len(completions)-1] } } } return completions, directive }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/get_notes_test.go
pkg/cmd/get_notes_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "testing" release "helm.sh/helm/v4/pkg/release/v1" ) func TestGetNotesCmd(t *testing.T) { tests := []cmdTestCase{{ name: "get notes of a deployed release", cmd: "get notes the-limerick", golden: "output/get-notes.txt", rels: []*release.Release{release.Mock(&release.MockReleaseOptions{Name: "the-limerick"})}, }, { name: "get notes without args", cmd: "get notes", golden: "output/get-notes-no-args.txt", wantError: true, }} runTestCmd(t, tests) } func TestGetNotesCompletion(t *testing.T) { checkReleaseCompletion(t, "get notes", false) } func TestGetNotesRevisionCompletion(t *testing.T) { revisionFlagCompletionTest(t, "get notes") } func TestGetNotesFileCompletion(t *testing.T) { checkFileCompletion(t, "get notes", false) checkFileCompletion(t, "get notes myrelease", false) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/search_test.go
pkg/cmd/search_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import "testing" func TestSearchFileCompletion(t *testing.T) { checkFileCompletion(t, "search", false) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/get_test.go
pkg/cmd/get_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "testing" ) func TestGetFileCompletion(t *testing.T) { checkFileCompletion(t, "get", false) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/plugin_package.go
pkg/cmd/plugin_package.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "bytes" "errors" "fmt" "io" "os" "path/filepath" "syscall" "github.com/spf13/cobra" "golang.org/x/term" "helm.sh/helm/v4/internal/plugin" "helm.sh/helm/v4/pkg/cmd/require" "helm.sh/helm/v4/pkg/provenance" ) const pluginPackageDesc = ` This command packages a Helm plugin directory into a tarball. By default, the command will generate a provenance file signed with a PGP key. This ensures the plugin can be verified after installation. Use --sign=false to skip signing (not recommended for distribution). ` type pluginPackageOptions struct { sign bool keyring string key string passphraseFile string pluginPath string destination string } func newPluginPackageCmd(out io.Writer) *cobra.Command { o := &pluginPackageOptions{} cmd := &cobra.Command{ Use: "package [PATH]", Short: "package a plugin directory into a plugin archive", Long: pluginPackageDesc, Args: require.ExactArgs(1), RunE: func(_ *cobra.Command, args []string) error { o.pluginPath = args[0] return o.run(out) }, } f := cmd.Flags() f.BoolVar(&o.sign, "sign", true, "use a PGP private key to sign this plugin") f.StringVar(&o.key, "key", "", "name of the key to use when signing. Used if --sign is true") f.StringVar(&o.keyring, "keyring", defaultKeyring(), "location of a public keyring") f.StringVar(&o.passphraseFile, "passphrase-file", "", "location of a file which contains the passphrase for the signing key. Use \"-\" to read from stdin.") f.StringVarP(&o.destination, "destination", "d", ".", "location to write the plugin tarball.") return cmd } func (o *pluginPackageOptions) run(out io.Writer) error { // Check if the plugin path exists and is a directory fi, err := os.Stat(o.pluginPath) if err != nil { return err } if !fi.IsDir() { return fmt.Errorf("plugin package only supports directories, not tarballs") } // Load and validate plugin metadata pluginMeta, err := plugin.LoadDir(o.pluginPath) if err != nil { return fmt.Errorf("invalid plugin directory: %w", err) } // Create destination directory if needed if err := os.MkdirAll(o.destination, 0755); err != nil { return err } // If signing is requested, prepare the signer first var signer *provenance.Signatory if o.sign { // Load the signing key signer, err = provenance.NewFromKeyring(o.keyring, o.key) if err != nil { return fmt.Errorf("error reading from keyring: %w", err) } // Get passphrase passphraseFetcher := o.promptUser if o.passphraseFile != "" { passphraseFetcher, err = o.passphraseFileFetcher() if err != nil { return err } } // Decrypt the key if err := signer.DecryptKey(passphraseFetcher); err != nil { return err } } else { // User explicitly disabled signing fmt.Fprintf(out, "WARNING: Skipping plugin signing. This is not recommended for plugins intended for distribution.\n") } // Now create the tarball (only after signing prerequisites are met) // Use plugin metadata for filename: PLUGIN_NAME-SEMVER.tgz metadata := pluginMeta.Metadata() filename := fmt.Sprintf("%s-%s.tgz", metadata.Name, metadata.Version) tarballPath := filepath.Join(o.destination, filename) tarFile, err := os.Create(tarballPath) if err != nil { return fmt.Errorf("failed to create tarball: %w", err) } defer tarFile.Close() if err := plugin.CreatePluginTarball(o.pluginPath, metadata.Name, tarFile); err != nil { os.Remove(tarballPath) return fmt.Errorf("failed to create plugin tarball: %w", err) } tarFile.Close() // Ensure file is closed before signing // If signing was requested, sign the tarball if o.sign { // Read the tarball data tarballData, err := os.ReadFile(tarballPath) if err != nil { os.Remove(tarballPath) return fmt.Errorf("failed to read tarball for signing: %w", err) } // Sign the plugin tarball data sig, err := plugin.SignPlugin(tarballData, filepath.Base(tarballPath), signer) if err != nil { os.Remove(tarballPath) return fmt.Errorf("failed to sign plugin: %w", err) } // Write the signature provFile := tarballPath + ".prov" if err := os.WriteFile(provFile, []byte(sig), 0644); err != nil { os.Remove(tarballPath) return err } fmt.Fprintf(out, "Successfully signed. Signature written to: %s\n", provFile) } fmt.Fprintf(out, "Successfully packaged plugin and saved it to: %s\n", tarballPath) return nil } func (o *pluginPackageOptions) promptUser(name string) ([]byte, error) { fmt.Printf("Password for key %q > ", name) pw, err := term.ReadPassword(int(syscall.Stdin)) fmt.Println() return pw, err } func (o *pluginPackageOptions) passphraseFileFetcher() (provenance.PassphraseFetcher, error) { file, err := openPassphraseFile(o.passphraseFile, os.Stdin) if err != nil { return nil, err } defer file.Close() // Read the entire passphrase passphrase, err := io.ReadAll(file) if err != nil { return nil, err } // Trim any trailing newline characters (both \n and \r\n) passphrase = bytes.TrimRight(passphrase, "\r\n") return func(_ string) ([]byte, error) { return passphrase, nil }, nil } // copied from action.openPassphraseFile // TODO: should we move this to pkg/action so we can reuse the func from there? func openPassphraseFile(passphraseFile string, stdin *os.File) (*os.File, error) { if passphraseFile == "-" { stat, err := stdin.Stat() if err != nil { return nil, err } if (stat.Mode() & os.ModeNamedPipe) == 0 { return nil, errors.New("specified reading passphrase from stdin, without input on stdin") } return stdin, nil } return os.Open(passphraseFile) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/completion.go
pkg/cmd/completion.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "io" "os" "path/filepath" "github.com/spf13/cobra" "helm.sh/helm/v4/pkg/cmd/require" ) const completionDesc = ` Generate autocompletion scripts for Helm for the specified shell. ` const bashCompDesc = ` Generate the autocompletion script for Helm for the bash shell. To load completions in your current shell session: source <(helm completion bash) To load completions for every new session, execute once: - Linux: helm completion bash > /etc/bash_completion.d/helm - MacOS: helm completion bash > /usr/local/etc/bash_completion.d/helm ` const zshCompDesc = ` Generate the autocompletion script for Helm for the zsh shell. To load completions in your current shell session: source <(helm completion zsh) To load completions for every new session, execute once: helm completion zsh > "${fpath[1]}/_helm" ` const fishCompDesc = ` Generate the autocompletion script for Helm for the fish shell. To load completions in your current shell session: helm completion fish | source To load completions for every new session, execute once: helm completion fish > ~/.config/fish/completions/helm.fish You will need to start a new shell for this setup to take effect. ` const powershellCompDesc = ` Generate the autocompletion script for powershell. To load completions in your current shell session: PS C:\> helm completion powershell | Out-String | Invoke-Expression To load completions for every new session, add the output of the above command to your powershell profile. ` const ( noDescFlagName = "no-descriptions" noDescFlagText = "disable completion descriptions" ) var disableCompDescriptions bool func newCompletionCmd(out io.Writer) *cobra.Command { cmd := &cobra.Command{ Use: "completion", Short: "generate autocompletion scripts for the specified shell", Long: completionDesc, Args: require.NoArgs, } bash := &cobra.Command{ Use: "bash", Short: "generate autocompletion script for bash", Long: bashCompDesc, Args: require.NoArgs, ValidArgsFunction: noMoreArgsCompFunc, RunE: func(cmd *cobra.Command, _ []string) error { return runCompletionBash(out, cmd) }, } bash.Flags().BoolVar(&disableCompDescriptions, noDescFlagName, false, noDescFlagText) zsh := &cobra.Command{ Use: "zsh", Short: "generate autocompletion script for zsh", Long: zshCompDesc, Args: require.NoArgs, ValidArgsFunction: noMoreArgsCompFunc, RunE: func(cmd *cobra.Command, _ []string) error { return runCompletionZsh(out, cmd) }, } zsh.Flags().BoolVar(&disableCompDescriptions, noDescFlagName, false, noDescFlagText) fish := &cobra.Command{ Use: "fish", Short: "generate autocompletion script for fish", Long: fishCompDesc, Args: require.NoArgs, ValidArgsFunction: noMoreArgsCompFunc, RunE: func(cmd *cobra.Command, _ []string) error { return runCompletionFish(out, cmd) }, } fish.Flags().BoolVar(&disableCompDescriptions, noDescFlagName, false, noDescFlagText) powershell := &cobra.Command{ Use: "powershell", Short: "generate autocompletion script for powershell", Long: powershellCompDesc, Args: require.NoArgs, ValidArgsFunction: noMoreArgsCompFunc, RunE: func(cmd *cobra.Command, _ []string) error { return runCompletionPowershell(out, cmd) }, } powershell.Flags().BoolVar(&disableCompDescriptions, noDescFlagName, false, noDescFlagText) cmd.AddCommand(bash, zsh, fish, powershell) return cmd } func runCompletionBash(out io.Writer, cmd *cobra.Command) error { err := cmd.Root().GenBashCompletionV2(out, !disableCompDescriptions) // In case the user renamed the helm binary (e.g., to be able to run // both helm2 and helm3), we hook the new binary name to the completion function if binary := filepath.Base(os.Args[0]); binary != "helm" { renamedBinaryHook := ` # Hook the command used to generate the completion script # to the helm completion function to handle the case where # the user renamed the helm binary if [[ $(type -t compopt) = "builtin" ]]; then complete -o default -F __start_helm %[1]s else complete -o default -o nospace -F __start_helm %[1]s fi ` fmt.Fprintf(out, renamedBinaryHook, binary) } return err } func runCompletionZsh(out io.Writer, cmd *cobra.Command) error { var err error if disableCompDescriptions { err = cmd.Root().GenZshCompletionNoDesc(out) } else { err = cmd.Root().GenZshCompletion(out) } // In case the user renamed the helm binary (e.g., to be able to run // both helm2 and helm3), we hook the new binary name to the completion function if binary := filepath.Base(os.Args[0]); binary != "helm" { renamedBinaryHook := ` # Hook the command used to generate the completion script # to the helm completion function to handle the case where # the user renamed the helm binary compdef _helm %[1]s ` fmt.Fprintf(out, renamedBinaryHook, binary) } // Cobra doesn't source zsh completion file, explicitly doing it here fmt.Fprintf(out, "compdef _helm helm") return err } func runCompletionFish(out io.Writer, cmd *cobra.Command) error { return cmd.Root().GenFishCompletion(out, !disableCompDescriptions) } func runCompletionPowershell(out io.Writer, cmd *cobra.Command) error { if disableCompDescriptions { return cmd.Root().GenPowerShellCompletion(out) } return cmd.Root().GenPowerShellCompletionWithDesc(out) } // noMoreArgsCompFunc deactivates file completion when doing argument shell completion. // It also provides some ActiveHelp to indicate no more arguments are accepted. func noMoreArgsCompFunc(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) { return noMoreArgsComp() } // noMoreArgsComp deactivates file completion when doing argument shell completion. // It also provides some ActiveHelp to indicate no more arguments are accepted. func noMoreArgsComp() ([]string, cobra.ShellCompDirective) { activeHelpMsg := "This command does not take any more arguments (but may accept flags)." return cobra.AppendActiveHelp(nil, activeHelpMsg), cobra.ShellCompDirectiveNoFileComp }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/env.go
pkg/cmd/env.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "io" "sort" "github.com/spf13/cobra" "helm.sh/helm/v4/pkg/cmd/require" ) var envHelp = ` Env prints out all the environment information in use by Helm. ` func newEnvCmd(out io.Writer) *cobra.Command { cmd := &cobra.Command{ Use: "env", Short: "helm client environment information", Long: envHelp, Args: require.MaximumNArgs(1), ValidArgsFunction: func(_ *cobra.Command, args []string, _ string) ([]string, cobra.ShellCompDirective) { if len(args) == 0 { keys := getSortedEnvVarKeys() return keys, cobra.ShellCompDirectiveNoFileComp } return noMoreArgsComp() }, Run: func(_ *cobra.Command, args []string) { envVars := settings.EnvVars() if len(args) == 0 { // Sort the variables by alphabetical order. // This allows for a constant output across calls to 'helm env'. keys := getSortedEnvVarKeys() for _, k := range keys { fmt.Fprintf(out, "%s=\"%s\"\n", k, envVars[k]) } } else { fmt.Fprintf(out, "%s\n", envVars[args[0]]) } }, } return cmd } func getSortedEnvVarKeys() []string { envVars := settings.EnvVars() var keys []string for k := range envVars { keys = append(keys, k) } sort.Strings(keys) return keys }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/profiling.go
pkg/cmd/profiling.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "errors" "fmt" "os" "runtime" "runtime/pprof" ) var ( cpuProfileFile *os.File cpuProfilePath string memProfilePath string ) func init() { cpuProfilePath = os.Getenv("HELM_PPROF_CPU_PROFILE") memProfilePath = os.Getenv("HELM_PPROF_MEM_PROFILE") } // startProfiling starts profiling CPU usage if HELM_PPROF_CPU_PROFILE is set // to a file path. It returns an error if the file could not be created or // CPU profiling could not be started. func startProfiling() error { if cpuProfilePath != "" { var err error cpuProfileFile, err = os.Create(cpuProfilePath) if err != nil { return fmt.Errorf("could not create CPU profile: %w", err) } if err := pprof.StartCPUProfile(cpuProfileFile); err != nil { cpuProfileFile.Close() cpuProfileFile = nil return fmt.Errorf("could not start CPU profile: %w", err) } } return nil } // stopProfiling stops profiling CPU and memory usage. // It writes memory profile to the file path specified in HELM_PPROF_MEM_PROFILE // environment variable. func stopProfiling() error { errs := []error{} // Stop CPU profiling if it was started if cpuProfileFile != nil { pprof.StopCPUProfile() err := cpuProfileFile.Close() if err != nil { errs = append(errs, err) } cpuProfileFile = nil } if memProfilePath != "" { f, err := os.Create(memProfilePath) if err != nil { errs = append(errs, err) } defer f.Close() runtime.GC() // get up-to-date statistics if err := pprof.WriteHeapProfile(f); err != nil { errs = append(errs, err) } } if err := errors.Join(errs...); err != nil { return fmt.Errorf("error(s) while stopping profiling: %w", err) } return nil }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/template_test.go
pkg/cmd/template_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "path/filepath" "testing" ) var chartPath = "testdata/testcharts/subchart" func TestTemplateCmd(t *testing.T) { deletevalchart := "testdata/testcharts/issue-9027" tests := []cmdTestCase{ { name: "check name", cmd: fmt.Sprintf("template '%s'", chartPath), golden: "output/template.txt", }, { name: "check set name", cmd: fmt.Sprintf("template '%s' --set service.name=apache", chartPath), golden: "output/template-set.txt", }, { name: "check values files", cmd: fmt.Sprintf("template '%s' --values '%s'", chartPath, filepath.Join(chartPath, "/charts/subchartA/values.yaml")), golden: "output/template-values-files.txt", }, { name: "check name template", cmd: fmt.Sprintf(`template '%s' --name-template='foobar-{{ b64enc "abc" | lower }}-baz'`, chartPath), golden: "output/template-name-template.txt", }, { name: "check no args", cmd: "template", wantError: true, golden: "output/template-no-args.txt", }, { name: "check library chart", cmd: fmt.Sprintf("template '%s'", "testdata/testcharts/lib-chart"), wantError: true, golden: "output/template-lib-chart.txt", }, { name: "check chart bad type", cmd: fmt.Sprintf("template '%s'", "testdata/testcharts/chart-bad-type"), wantError: true, golden: "output/template-chart-bad-type.txt", }, { name: "check chart with dependency which is an app chart acting as a library chart", cmd: fmt.Sprintf("template '%s'", "testdata/testcharts/chart-with-template-lib-dep"), golden: "output/template-chart-with-template-lib-dep.txt", }, { name: "check chart with dependency which is an app chart archive acting as a library chart", cmd: fmt.Sprintf("template '%s'", "testdata/testcharts/chart-with-template-lib-archive-dep"), golden: "output/template-chart-with-template-lib-archive-dep.txt", }, { name: "check kube version", cmd: fmt.Sprintf("template --kube-version 1.16.0 '%s'", chartPath), golden: "output/template-with-kube-version.txt", }, { name: "check kube api versions", cmd: fmt.Sprintf("template --api-versions helm.k8s.io/test,helm.k8s.io/test2 '%s'", chartPath), golden: "output/template-with-api-version.txt", }, { name: "check kube api versions", cmd: fmt.Sprintf("template --api-versions helm.k8s.io/test --api-versions helm.k8s.io/test2 '%s'", chartPath), golden: "output/template-with-api-version.txt", }, { name: "template with CRDs", cmd: fmt.Sprintf("template '%s' --include-crds", chartPath), golden: "output/template-with-crds.txt", }, { name: "template with show-only one", cmd: fmt.Sprintf("template '%s' --show-only templates/service.yaml", chartPath), golden: "output/template-show-only-one.txt", }, { name: "template with show-only multiple", cmd: fmt.Sprintf("template '%s' --show-only templates/service.yaml --show-only charts/subcharta/templates/service.yaml", chartPath), golden: "output/template-show-only-multiple.txt", }, { name: "template with show-only glob", cmd: fmt.Sprintf("template '%s' --show-only templates/subdir/role*", chartPath), golden: "output/template-show-only-glob.txt", // Repeat to ensure manifest ordering regressions are caught repeat: 10, }, { name: "sorted output of manifests (order of filenames, then order of objects within each YAML file)", cmd: fmt.Sprintf("template '%s'", "testdata/testcharts/object-order"), golden: "output/object-order.txt", // Helm previously used random file order. Repeat the test so we // don't accidentally get the expected result. repeat: 10, }, { name: "chart with template with invalid yaml", cmd: fmt.Sprintf("template '%s'", "testdata/testcharts/chart-with-template-with-invalid-yaml"), wantError: true, golden: "output/template-with-invalid-yaml.txt", }, { name: "chart with template with invalid yaml (--debug)", cmd: fmt.Sprintf("template '%s' --debug", "testdata/testcharts/chart-with-template-with-invalid-yaml"), wantError: true, golden: "output/template-with-invalid-yaml-debug.txt", }, { name: "template skip-tests", cmd: fmt.Sprintf(`template '%s' --skip-tests`, chartPath), golden: "output/template-skip-tests.txt", }, { // This test case is to ensure the case where specified dependencies // in the Chart.yaml and those where the Chart.yaml don't have them // specified are the same. name: "ensure nil/null values pass to subcharts delete values", cmd: fmt.Sprintf("template '%s'", deletevalchart), golden: "output/issue-9027.txt", }, { // Ensure that parent chart values take precedence over imported values name: "template with imported subchart values ensuring import", cmd: fmt.Sprintf("template '%s' --set configmap.enabled=true --set subchartb.enabled=true", chartPath), golden: "output/template-subchart-cm.txt", }, { // Ensure that user input values take precedence over imported // values from sub-charts. name: "template with imported subchart values set with --set", cmd: fmt.Sprintf("template '%s' --set configmap.enabled=true --set subchartb.enabled=true --set configmap.value=baz", chartPath), golden: "output/template-subchart-cm-set.txt", }, { // Ensure that user input values take precedence over imported // values from sub-charts when passed by file name: "template with imported subchart values set with --set", cmd: fmt.Sprintf("template '%s' -f %s/extra_values.yaml", chartPath, chartPath), golden: "output/template-subchart-cm-set-file.txt", }, } runTestCmd(t, tests) } func TestTemplateVersionCompletion(t *testing.T) { repoFile := "testdata/helmhome/helm/repositories.yaml" repoCache := "testdata/helmhome/helm/repository" repoSetup := fmt.Sprintf("--repository-config %s --repository-cache %s", repoFile, repoCache) tests := []cmdTestCase{{ name: "completion for template version flag with release name", cmd: fmt.Sprintf("%s __complete template releasename testing/alpine --version ''", repoSetup), golden: "output/version-comp.txt", }, { name: "completion for template version flag with generate-name", cmd: fmt.Sprintf("%s __complete template --generate-name testing/alpine --version ''", repoSetup), golden: "output/version-comp.txt", }, { name: "completion for template version flag too few args", cmd: fmt.Sprintf("%s __complete template testing/alpine --version ''", repoSetup), golden: "output/version-invalid-comp.txt", }, { name: "completion for template version flag too many args", cmd: fmt.Sprintf("%s __complete template releasename testing/alpine badarg --version ''", repoSetup), golden: "output/version-invalid-comp.txt", }, { name: "completion for template version flag invalid chart", cmd: fmt.Sprintf("%s __complete template releasename invalid/invalid --version ''", repoSetup), golden: "output/version-invalid-comp.txt", }} runTestCmd(t, tests) } func TestTemplateFileCompletion(t *testing.T) { checkFileCompletion(t, "template", false) checkFileCompletion(t, "template --generate-name", true) checkFileCompletion(t, "template myname", true) checkFileCompletion(t, "template myname mychart", false) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/repo_test.go
pkg/cmd/repo_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "testing" ) func TestRepoFileCompletion(t *testing.T) { checkFileCompletion(t, "repo", false) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/pull.go
pkg/cmd/pull.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "io" "log" "log/slog" "github.com/spf13/cobra" "helm.sh/helm/v4/pkg/action" "helm.sh/helm/v4/pkg/cmd/require" ) const pullDesc = ` Retrieve a package from a package repository, and download it locally. This is useful for fetching packages to inspect, modify, or repackage. It can also be used to perform cryptographic verification of a chart without installing the chart. There are options for unpacking the chart after download. This will create a directory for the chart and uncompress into that directory. If the --verify flag is specified, the requested chart MUST have a provenance file, and MUST pass the verification process. Failure in any part of this will result in an error, and the chart will not be saved locally. ` func newPullCmd(cfg *action.Configuration, out io.Writer) *cobra.Command { client := action.NewPull(action.WithConfig(cfg)) cmd := &cobra.Command{ Use: "pull [chart URL | repo/chartname] [...]", Short: "download a chart from a repository and (optionally) unpack it in local directory", Aliases: []string{"fetch"}, Long: pullDesc, Args: require.MinimumNArgs(1), ValidArgsFunction: func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { if len(args) != 0 { return nil, cobra.ShellCompDirectiveNoFileComp } return compListCharts(toComplete, false) }, RunE: func(_ *cobra.Command, args []string) error { client.Settings = settings if client.Version == "" && client.Devel { slog.Debug("setting version to >0.0.0-0") client.Version = ">0.0.0-0" } registryClient, err := newRegistryClient(client.CertFile, client.KeyFile, client.CaFile, client.InsecureSkipTLSVerify, client.PlainHTTP, client.Username, client.Password) if err != nil { return fmt.Errorf("missing registry client: %w", err) } client.SetRegistryClient(registryClient) for i := range args { output, err := client.Run(args[i]) if err != nil { return err } fmt.Fprint(out, output) } return nil }, } f := cmd.Flags() f.BoolVar(&client.Devel, "devel", false, "use development versions, too. Equivalent to version '>0.0.0-0'. If --version is set, this is ignored.") f.BoolVar(&client.Untar, "untar", false, "if set to true, will untar the chart after downloading it") f.BoolVar(&client.VerifyLater, "prov", false, "fetch the provenance file, but don't perform verification") f.StringVar(&client.UntarDir, "untardir", ".", "if untar is specified, this flag specifies the name of the directory into which the chart is expanded") f.StringVarP(&client.DestDir, "destination", "d", ".", "location to write the chart. If this and untardir are specified, untardir is appended to this") addChartPathOptionsFlags(f, &client.ChartPathOptions) err := cmd.RegisterFlagCompletionFunc("version", func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { if len(args) != 1 { return nil, cobra.ShellCompDirectiveNoFileComp } return compVersionFlag(args[0], toComplete) }) if err != nil { log.Fatal(err) } return cmd }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/version.go
pkg/cmd/version.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "io" "text/template" "github.com/spf13/cobra" "helm.sh/helm/v4/internal/version" "helm.sh/helm/v4/pkg/cmd/require" ) const versionDesc = ` Show the version for Helm. This will print a representation the version of Helm. The output will look something like this: version.BuildInfo{Version:"v3.2.1", GitCommit:"fe51cd1e31e6a202cba7dead9552a6d418ded79a", GitTreeState:"clean", GoVersion:"go1.13.10"} - Version is the semantic version of the release. - GitCommit is the SHA for the commit that this version was built from. - GitTreeState is "clean" if there are no local code changes when this binary was built, and "dirty" if the binary was built from locally modified code. - GoVersion is the version of Go that was used to compile Helm. When using the --template flag the following properties are available to use in the template: - .Version contains the semantic version of Helm - .GitCommit is the git commit - .GitTreeState is the state of the git tree when Helm was built - .GoVersion contains the version of Go that Helm was compiled with For example, --template='Version: {{.Version}}' outputs 'Version: v3.2.1'. ` type versionOptions struct { short bool template string } func newVersionCmd(out io.Writer) *cobra.Command { o := &versionOptions{} cmd := &cobra.Command{ Use: "version", Short: "print the helm version information", Long: versionDesc, Args: require.NoArgs, ValidArgsFunction: noMoreArgsCompFunc, RunE: func(_ *cobra.Command, _ []string) error { return o.run(out) }, } f := cmd.Flags() f.BoolVar(&o.short, "short", false, "print the version number") f.StringVar(&o.template, "template", "", "template for version string format") return cmd } func (o *versionOptions) run(out io.Writer) error { if o.template != "" { tt, err := template.New("_").Parse(o.template) if err != nil { return err } return tt.Execute(out, version.Get()) } fmt.Fprintln(out, formatVersion(o.short)) return nil } func formatVersion(short bool) string { v := version.Get() if short { if len(v.GitCommit) >= 7 { return fmt.Sprintf("%s+g%s", v.Version, v.GitCommit[:7]) } return version.GetVersion() } return fmt.Sprintf("%#v", v) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/search_hub_test.go
pkg/cmd/search_hub_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "net/http" "net/http/httptest" "testing" ) func TestSearchHubCmd(t *testing.T) { // Setup 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"}}}}]}` ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { fmt.Fprintln(w, searchResult) })) defer ts.Close() // The expected output has the URL to the mocked search service in it // Trailing spaces are necessary to preserve in "expected" as the uitable package adds // them during printing. var expected = fmt.Sprintf(`URL CHART VERSION APP VERSION DESCRIPTION %s/charts/stable/phpmyadmin 3.0.0 4.9.0-1 phpMyAdmin is an mysql administration frontend %s/charts/bitnami/phpmyadmin 3.0.0 4.9.0-1 phpMyAdmin is an mysql administration frontend `, ts.URL, ts.URL) testcmd := "search hub --endpoint " + ts.URL + " maria" storage := storageFixture() _, out, err := executeActionCommandC(storage, testcmd) if err != nil { t.Errorf("unexpected error, %s", err) } if out != expected { t.Error("expected and actual output did not match") t.Log(out) t.Log(expected) } } func TestSearchHubListRepoCmd(t *testing.T) { // Setup 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"}}}}]}` ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { fmt.Fprintln(w, searchResult) })) defer ts.Close() // The expected output has the URL to the mocked search service in it // Trailing spaces are necessary to preserve in "expected" as the uitable package adds // them during printing. var expected = fmt.Sprintf(`URL CHART VERSION APP VERSION DESCRIPTION REPO URL %s/charts/stable/phpmyadmin 3.0.0 4.9.0-1 phpMyAdmin is an mysql administration frontend https://charts.helm.sh/stable %s/charts/bitnami/phpmyadmin 3.0.0 4.9.0-1 phpMyAdmin is an mysql administration frontend https://charts.bitnami.com `, ts.URL, ts.URL) testcmd := "search hub --list-repo-url --endpoint " + ts.URL + " maria" storage := storageFixture() _, out, err := executeActionCommandC(storage, testcmd) if err != nil { t.Errorf("unexpected error, %s", err) } if out != expected { t.Error("expected and actual output did not match") t.Log(out) t.Log(expected) } } func TestSearchHubOutputCompletion(t *testing.T) { outputFlagCompletionTest(t, "search hub") } func TestSearchHubFileCompletion(t *testing.T) { checkFileCompletion(t, "search hub", true) // File completion may be useful when inputting a keyword } func TestSearchHubCmd_FailOnNoResponseTests(t *testing.T) { var ( searchResult = `{"data":[]}` noResultFoundErr = "Error: no results found\n" noResultFoundWarn = "No results found\n" noResultFoundWarnInList = "[]\n" ) type testCase struct { name string cmd string response string expected string wantErr bool } var tests = []testCase{ { name: "Search hub with no results in response", cmd: `search hub maria`, response: searchResult, expected: noResultFoundWarn, wantErr: false, }, { name: "Search hub with no results in response and output JSON", cmd: `search hub maria --output json`, response: searchResult, expected: noResultFoundWarnInList, wantErr: false, }, { name: "Search hub with no results in response and output YAML", cmd: `search hub maria --output yaml`, response: searchResult, expected: noResultFoundWarnInList, wantErr: false, }, { name: "Search hub with no results in response and --fail-on-no-result enabled, expected failure", cmd: `search hub maria --fail-on-no-result`, response: searchResult, expected: noResultFoundErr, wantErr: true, }, { name: "Search hub with no results in response, output JSON and --fail-on-no-result enabled, expected failure", cmd: `search hub maria --fail-on-no-result --output json`, response: searchResult, expected: noResultFoundErr, wantErr: true, }, { name: "Search hub with no results in response, output YAML and --fail-on-no-result enabled, expected failure", cmd: `search hub maria --fail-on-no-result --output yaml`, response: searchResult, expected: noResultFoundErr, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Setup a mock search service ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { fmt.Fprintln(w, tt.response) })) defer ts.Close() // Add mock server URL to command tt.cmd += " --endpoint " + ts.URL storage := storageFixture() _, out, err := executeActionCommandC(storage, tt.cmd) if tt.wantErr { if err == nil { t.Errorf("expected error due to no record in response, got nil") } } else { if err != nil { t.Errorf("unexpected error, got %q", err) } } if out != tt.expected { t.Errorf("expected and actual output did not match\n"+ "expected: %q\n"+ "actual : %q", tt.expected, out) } }) } }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/dependency_build.go
pkg/cmd/dependency_build.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "io" "os" "path/filepath" "github.com/spf13/cobra" "k8s.io/client-go/util/homedir" "helm.sh/helm/v4/pkg/action" "helm.sh/helm/v4/pkg/cmd/require" "helm.sh/helm/v4/pkg/downloader" "helm.sh/helm/v4/pkg/getter" ) const dependencyBuildDesc = ` Build out the charts/ directory from the Chart.lock file. Build is used to reconstruct a chart's dependencies to the state specified in the lock file. This will not re-negotiate dependencies, as 'helm dependency update' does. If no lock file is found, 'helm dependency build' will mirror the behavior of 'helm dependency update'. ` func newDependencyBuildCmd(out io.Writer) *cobra.Command { client := action.NewDependency() cmd := &cobra.Command{ Use: "build CHART", Short: "rebuild the charts/ directory based on the Chart.lock file", Long: dependencyBuildDesc, Args: require.MaximumNArgs(1), RunE: func(_ *cobra.Command, args []string) error { chartpath := "." if len(args) > 0 { chartpath = filepath.Clean(args[0]) } registryClient, err := newRegistryClient(client.CertFile, client.KeyFile, client.CaFile, client.InsecureSkipTLSVerify, client.PlainHTTP, client.Username, client.Password) if err != nil { return fmt.Errorf("missing registry client: %w", err) } man := &downloader.Manager{ Out: out, ChartPath: chartpath, Keyring: client.Keyring, SkipUpdate: client.SkipRefresh, Getters: getter.All(settings), RegistryClient: registryClient, RepositoryConfig: settings.RepositoryConfig, RepositoryCache: settings.RepositoryCache, ContentCache: settings.ContentCache, Debug: settings.Debug, } if client.Verify { man.Verify = downloader.VerifyIfPossible } err = man.Build() if e, ok := err.(downloader.ErrRepoNotFound); ok { return fmt.Errorf("%s. Please add the missing repos via 'helm repo add'", e.Error()) } return err }, } f := cmd.Flags() addDependencySubcommandFlags(f, client) return cmd } // defaultKeyring returns the expanded path to the default keyring. func defaultKeyring() string { if v, ok := os.LookupEnv("GNUPGHOME"); ok { return filepath.Join(v, "pubring.gpg") } return filepath.Join(homedir.HomeDir(), ".gnupg", "pubring.gpg") }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/get.go
pkg/cmd/get.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "io" "github.com/spf13/cobra" "helm.sh/helm/v4/pkg/action" "helm.sh/helm/v4/pkg/cmd/require" ) var getHelp = ` This command consists of multiple subcommands which can be used to get extended information about the release, including: - The values used to generate the release - The generated manifest file - The notes provided by the chart of the release - The hooks associated with the release - The metadata of the release ` func newGetCmd(cfg *action.Configuration, out io.Writer) *cobra.Command { cmd := &cobra.Command{ Use: "get", Short: "download extended information of a named release", Long: getHelp, Args: require.NoArgs, } cmd.AddCommand(newGetAllCmd(cfg, out)) cmd.AddCommand(newGetValuesCmd(cfg, out)) cmd.AddCommand(newGetManifestCmd(cfg, out)) cmd.AddCommand(newGetHooksCmd(cfg, out)) cmd.AddCommand(newGetNotesCmd(cfg, out)) cmd.AddCommand(newGetMetadataCmd(cfg, out)) return cmd }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/get_hooks_test.go
pkg/cmd/get_hooks_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "testing" release "helm.sh/helm/v4/pkg/release/v1" ) func TestGetHooks(t *testing.T) { tests := []cmdTestCase{{ name: "get hooks with release", cmd: "get hooks aeneas", golden: "output/get-hooks.txt", rels: []*release.Release{release.Mock(&release.MockReleaseOptions{Name: "aeneas"})}, }, { name: "get hooks without args", cmd: "get hooks", golden: "output/get-hooks-no-args.txt", wantError: true, }} runTestCmd(t, tests) } func TestGetHooksCompletion(t *testing.T) { checkReleaseCompletion(t, "get hooks", false) } func TestGetHooksRevisionCompletion(t *testing.T) { revisionFlagCompletionTest(t, "get hooks") } func TestGetHooksFileCompletion(t *testing.T) { checkFileCompletion(t, "get hooks", false) checkFileCompletion(t, "get hooks myrelease", false) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/uninstall_test.go
pkg/cmd/uninstall_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "testing" "helm.sh/helm/v4/pkg/release/common" release "helm.sh/helm/v4/pkg/release/v1" ) func TestUninstall(t *testing.T) { tests := []cmdTestCase{ { name: "basic uninstall", cmd: "uninstall aeneas", golden: "output/uninstall.txt", rels: []*release.Release{release.Mock(&release.MockReleaseOptions{Name: "aeneas"})}, }, { name: "multiple uninstall", cmd: "uninstall aeneas aeneas2", golden: "output/uninstall-multiple.txt", rels: []*release.Release{ release.Mock(&release.MockReleaseOptions{Name: "aeneas"}), release.Mock(&release.MockReleaseOptions{Name: "aeneas2"}), }, }, { name: "uninstall with timeout", cmd: "uninstall aeneas --timeout 120s", golden: "output/uninstall-timeout.txt", rels: []*release.Release{release.Mock(&release.MockReleaseOptions{Name: "aeneas"})}, }, { name: "uninstall without hooks", cmd: "uninstall aeneas --no-hooks", golden: "output/uninstall-no-hooks.txt", rels: []*release.Release{release.Mock(&release.MockReleaseOptions{Name: "aeneas"})}, }, { name: "keep history", cmd: "uninstall aeneas --keep-history", golden: "output/uninstall-keep-history.txt", rels: []*release.Release{release.Mock(&release.MockReleaseOptions{Name: "aeneas"})}, }, { name: "keep history with earlier deployed release", cmd: "uninstall aeneas --keep-history", golden: "output/uninstall-keep-history-earlier-deployed.txt", rels: []*release.Release{ release.Mock(&release.MockReleaseOptions{Name: "aeneas", Version: 1, Status: common.StatusDeployed}), release.Mock(&release.MockReleaseOptions{Name: "aeneas", Version: 2, Status: common.StatusFailed}), }, }, { name: "wait", cmd: "uninstall aeneas --wait", golden: "output/uninstall-wait.txt", rels: []*release.Release{release.Mock(&release.MockReleaseOptions{Name: "aeneas"})}, }, { name: "uninstall without release", cmd: "uninstall", golden: "output/uninstall-no-args.txt", wantError: true, }, } runTestCmd(t, tests) } func TestUninstallCompletion(t *testing.T) { checkReleaseCompletion(t, "uninstall", true) } func TestUninstallFileCompletion(t *testing.T) { checkFileCompletion(t, "uninstall", false) checkFileCompletion(t, "uninstall myrelease", false) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/registry_logout.go
pkg/cmd/registry_logout.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "io" "github.com/spf13/cobra" "helm.sh/helm/v4/pkg/action" "helm.sh/helm/v4/pkg/cmd/require" ) const registryLogoutDesc = ` Remove credentials stored for a remote registry. ` func newRegistryLogoutCmd(cfg *action.Configuration, out io.Writer) *cobra.Command { return &cobra.Command{ Use: "logout [host]", Short: "logout from a registry", Long: registryLogoutDesc, Args: require.MinimumNArgs(1), ValidArgsFunction: cobra.NoFileCompletions, RunE: func(_ *cobra.Command, args []string) error { hostname := args[0] return action.NewRegistryLogout(cfg).Run(out, hostname) }, } }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/template.go
pkg/cmd/template.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "bytes" "errors" "fmt" "io" "io/fs" "os" "path/filepath" "regexp" "slices" "sort" "strings" release "helm.sh/helm/v4/pkg/release/v1" "github.com/spf13/cobra" "helm.sh/helm/v4/pkg/action" "helm.sh/helm/v4/pkg/chart/common" "helm.sh/helm/v4/pkg/cli/values" "helm.sh/helm/v4/pkg/cmd/require" releaseutil "helm.sh/helm/v4/pkg/release/v1/util" ) const templateDesc = ` Render chart templates locally and display the output. Any values that would normally be looked up or retrieved in-cluster will be faked locally. Additionally, none of the server-side testing of chart validity (e.g. whether an API is supported) is done. To specify the Kubernetes API versions used for Capabilities.APIVersions, use the '--api-versions' flag. This flag can be specified multiple times or as a comma-separated list: $ helm template --api-versions networking.k8s.io/v1 --api-versions cert-manager.io/v1 mychart ./mychart or $ helm template --api-versions networking.k8s.io/v1,cert-manager.io/v1 mychart ./mychart ` func newTemplateCmd(cfg *action.Configuration, out io.Writer) *cobra.Command { var validate bool var includeCrds bool var skipTests bool client := action.NewInstall(cfg) valueOpts := &values.Options{} var kubeVersion string var extraAPIs []string var showFiles []string cmd := &cobra.Command{ Use: "template [NAME] [CHART]", Short: "locally render templates", Long: templateDesc, Args: require.MinimumNArgs(1), ValidArgsFunction: func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return compInstall(args, toComplete, client) }, RunE: func(cmd *cobra.Command, args []string) error { if kubeVersion != "" { parsedKubeVersion, err := common.ParseKubeVersion(kubeVersion) if err != nil { return fmt.Errorf("invalid kube version '%s': %s", kubeVersion, err) } client.KubeVersion = parsedKubeVersion } registryClient, err := newRegistryClient(client.CertFile, client.KeyFile, client.CaFile, client.InsecureSkipTLSVerify, client.PlainHTTP, client.Username, client.Password) if err != nil { return fmt.Errorf("missing registry client: %w", err) } client.SetRegistryClient(registryClient) dryRunStrategy, err := cmdGetDryRunFlagStrategy(cmd, true) if err != nil { return err } if validate { // Mimic deprecated --validate flag behavior by enabling server dry run dryRunStrategy = action.DryRunServer } client.DryRunStrategy = dryRunStrategy client.ReleaseName = "release-name" client.Replace = true // Skip the name check client.APIVersions = common.VersionSet(extraAPIs) client.IncludeCRDs = includeCrds rel, err := runInstall(args, client, valueOpts, out) if err != nil && !settings.Debug { if rel != nil { return fmt.Errorf("%w\n\nUse --debug flag to render out invalid YAML", err) } return err } // We ignore a potential error here because, when the --debug flag was specified, // we always want to print the YAML, even if it is not valid. The error is still returned afterwards. if rel != nil { var manifests bytes.Buffer fmt.Fprintln(&manifests, strings.TrimSpace(rel.Manifest)) if !client.DisableHooks { fileWritten := make(map[string]bool) for _, m := range rel.Hooks { if skipTests && isTestHook(m) { continue } if client.OutputDir == "" { fmt.Fprintf(&manifests, "---\n# Source: %s\n%s\n", m.Path, m.Manifest) } else { newDir := client.OutputDir if client.UseReleaseName { newDir = filepath.Join(client.OutputDir, client.ReleaseName) } _, err := os.Stat(filepath.Join(newDir, m.Path)) if err == nil { fileWritten[m.Path] = true } err = writeToFile(newDir, m.Path, m.Manifest, fileWritten[m.Path]) if err != nil { return err } } } } // if we have a list of files to render, then check that each of the // provided files exists in the chart. if len(showFiles) > 0 { // This is necessary to ensure consistent manifest ordering when using --show-only // with globs or directory names. splitManifests := releaseutil.SplitManifests(manifests.String()) manifestsKeys := make([]string, 0, len(splitManifests)) for k := range splitManifests { manifestsKeys = append(manifestsKeys, k) } sort.Sort(releaseutil.BySplitManifestsOrder(manifestsKeys)) manifestNameRegex := regexp.MustCompile("# Source: [^/]+/(.+)") var manifestsToRender []string for _, f := range showFiles { missing := true // Use linux-style filepath separators to unify user's input path f = filepath.ToSlash(f) for _, manifestKey := range manifestsKeys { manifest := splitManifests[manifestKey] submatch := manifestNameRegex.FindStringSubmatch(manifest) if len(submatch) == 0 { continue } manifestName := submatch[1] // manifest.Name is rendered using linux-style filepath separators on Windows as // well as macOS/linux. manifestPathSplit := strings.Split(manifestName, "/") // manifest.Path is connected using linux-style filepath separators on Windows as // well as macOS/linux manifestPath := strings.Join(manifestPathSplit, "/") // if the filepath provided matches a manifest path in the // chart, render that manifest if matched, _ := filepath.Match(f, manifestPath); !matched { continue } manifestsToRender = append(manifestsToRender, manifest) missing = false } if missing { return fmt.Errorf("could not find template %s in chart", f) } } for _, m := range manifestsToRender { fmt.Fprintf(out, "---\n%s\n", m) } } else { fmt.Fprintf(out, "%s", manifests.String()) } } return err }, } f := cmd.Flags() addInstallFlags(cmd, f, client, valueOpts) f.StringArrayVarP(&showFiles, "show-only", "s", []string{}, "only show manifests rendered from the given templates") f.StringVar(&client.OutputDir, "output-dir", "", "writes the executed templates to files in output-dir instead of stdout") f.BoolVar(&validate, "validate", false, "deprecated") f.MarkDeprecated("validate", "use '--dry-run=server' instead") f.BoolVar(&includeCrds, "include-crds", false, "include CRDs in the templated output") f.BoolVar(&skipTests, "skip-tests", false, "skip tests from templated output") f.BoolVar(&client.IsUpgrade, "is-upgrade", false, "set .Release.IsUpgrade instead of .Release.IsInstall") f.StringVar(&kubeVersion, "kube-version", "", "Kubernetes version used for Capabilities.KubeVersion") f.StringSliceVarP(&extraAPIs, "api-versions", "a", []string{}, "Kubernetes api versions used for Capabilities.APIVersions (multiple can be specified)") f.BoolVar(&client.UseReleaseName, "release-name", false, "use release name in the output-dir path.") f.String( "dry-run", "client", `simulates the operation either client-side or server-side. Must be either: "client", or "server". '--dry-run=client simulates the operation client-side only and avoids cluster connections. '--dry-run=server' simulates/validates the operation on the server, requiring cluster connectivity.`) f.Lookup("dry-run").NoOptDefVal = "unset" bindPostRenderFlag(cmd, &client.PostRenderer, settings) cmd.MarkFlagsMutuallyExclusive("validate", "dry-run") return cmd } func isTestHook(h *release.Hook) bool { return slices.Contains(h.Events, release.HookTest) } // The following functions (writeToFile, createOrOpenFile, and ensureDirectoryForFile) // are copied from the actions package. This is part of a change to correct a // bug introduced by #8156. As part of the todo to refactor renderResources // this duplicate code should be removed. It is added here so that the API // surface area is as minimally impacted as possible in fixing the issue. func writeToFile(outputDir string, name string, data string, appendData bool) error { outfileName := strings.Join([]string{outputDir, name}, string(filepath.Separator)) err := ensureDirectoryForFile(outfileName) if err != nil { return err } f, err := createOrOpenFile(outfileName, appendData) if err != nil { return err } defer f.Close() _, err = fmt.Fprintf(f, "---\n# Source: %s\n%s\n", name, data) if err != nil { return err } fmt.Printf("wrote %s\n", outfileName) return nil } func createOrOpenFile(filename string, appendData bool) (*os.File, error) { if appendData { return os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0600) } return os.Create(filename) } func ensureDirectoryForFile(file string) error { baseDir := filepath.Dir(file) _, err := os.Stat(baseDir) if err != nil && !errors.Is(err, fs.ErrNotExist) { return err } return os.MkdirAll(baseDir, 0755) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/plugin.go
pkg/cmd/plugin.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "io" "github.com/spf13/cobra" "helm.sh/helm/v4/internal/plugin" ) const pluginHelp = ` Manage client-side Helm plugins. ` func newPluginCmd(out io.Writer) *cobra.Command { cmd := &cobra.Command{ Use: "plugin", Short: "install, list, or uninstall Helm plugins", Long: pluginHelp, } cmd.AddCommand( newPluginInstallCmd(out), newPluginListCmd(out), newPluginUninstallCmd(out), newPluginUpdateCmd(out), newPluginPackageCmd(out), newPluginVerifyCmd(out), ) return cmd } // runHook will execute a plugin hook. func runHook(p plugin.Plugin, event string) error { pluginHook, ok := p.(plugin.PluginHook) if ok { return pluginHook.InvokeHook(event) } return nil }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/flags_test.go
pkg/cmd/flags_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "testing" "time" "github.com/stretchr/testify/require" "helm.sh/helm/v4/pkg/action" chart "helm.sh/helm/v4/pkg/chart/v2" "helm.sh/helm/v4/pkg/release/common" release "helm.sh/helm/v4/pkg/release/v1" ) func outputFlagCompletionTest(t *testing.T, cmdName string) { t.Helper() releasesMockWithStatus := func(info *release.Info, hooks ...*release.Hook) []*release.Release { info.LastDeployed = time.Unix(1452902400, 0).UTC() return []*release.Release{{ Name: "athos", Namespace: "default", Info: info, Chart: &chart.Chart{}, Hooks: hooks, }, { Name: "porthos", Namespace: "default", Info: info, Chart: &chart.Chart{}, Hooks: hooks, }, { Name: "aramis", Namespace: "default", Info: info, Chart: &chart.Chart{}, Hooks: hooks, }, { Name: "dartagnan", Namespace: "gascony", Info: info, Chart: &chart.Chart{}, Hooks: hooks, }} } tests := []cmdTestCase{{ name: "completion for output flag long and before arg", cmd: fmt.Sprintf("__complete %s --output ''", cmdName), golden: "output/output-comp.txt", rels: releasesMockWithStatus(&release.Info{ Status: common.StatusDeployed, }), }, { name: "completion for output flag long and after arg", cmd: fmt.Sprintf("__complete %s aramis --output ''", cmdName), golden: "output/output-comp.txt", rels: releasesMockWithStatus(&release.Info{ Status: common.StatusDeployed, }), }, { name: "completion for output flag short and before arg", cmd: fmt.Sprintf("__complete %s -o ''", cmdName), golden: "output/output-comp.txt", rels: releasesMockWithStatus(&release.Info{ Status: common.StatusDeployed, }), }, { name: "completion for output flag short and after arg", cmd: fmt.Sprintf("__complete %s aramis -o ''", cmdName), golden: "output/output-comp.txt", rels: releasesMockWithStatus(&release.Info{ Status: common.StatusDeployed, }), }, { name: "completion for output flag, no filter", cmd: fmt.Sprintf("__complete %s --output jso", cmdName), golden: "output/output-comp.txt", rels: releasesMockWithStatus(&release.Info{ Status: common.StatusDeployed, }), }} runTestCmd(t, tests) } func TestPostRendererFlagSetOnce(t *testing.T) { cfg := action.Configuration{} client := action.NewInstall(&cfg) settings.PluginsDirectory = "testdata/helmhome/helm/plugins" str := postRendererString{ options: &postRendererOptions{ renderer: &client.PostRenderer, settings: settings, }, } // Set the plugin name once err := str.Set("postrenderer-v1") require.NoError(t, err) // Set the plugin name again to the same value is not ok err = str.Set("postrenderer-v1") require.Error(t, err) // Set the plugin name again to a different value is not ok err = str.Set("cat") require.Error(t, err) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/repo_remove_test.go
pkg/cmd/repo_remove_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "bytes" "fmt" "os" "path/filepath" "strings" "testing" "helm.sh/helm/v4/pkg/helmpath" "helm.sh/helm/v4/pkg/repo/v1" "helm.sh/helm/v4/pkg/repo/v1/repotest" ) func TestRepoRemove(t *testing.T) { ts := repotest.NewTempServer( t, repotest.WithChartSourceGlob("testdata/testserver/*.*"), ) defer ts.Stop() rootDir := t.TempDir() repoFile := filepath.Join(rootDir, "repositories.yaml") const testRepoName = "test-name" b := bytes.NewBuffer(nil) rmOpts := repoRemoveOptions{ names: []string{testRepoName}, repoFile: repoFile, repoCache: rootDir, } if err := rmOpts.run(os.Stderr); err == nil { t.Errorf("Expected error removing %s, but did not get one.", testRepoName) } o := &repoAddOptions{ name: testRepoName, url: ts.URL(), repoFile: repoFile, } if err := o.run(os.Stderr); err != nil { t.Error(err) } cacheIndexFile, cacheChartsFile := createCacheFiles(rootDir, testRepoName) // Reset the buffer before running repo remove b.Reset() if err := rmOpts.run(b); err != nil { t.Errorf("Error removing %s from repositories", testRepoName) } if !strings.Contains(b.String(), "has been removed") { t.Errorf("Unexpected output: %s", b.String()) } testCacheFiles(t, cacheIndexFile, cacheChartsFile, testRepoName) f, err := repo.LoadFile(repoFile) if err != nil { t.Error(err) } if f.Has(testRepoName) { t.Errorf("%s was not successfully removed from repositories list", testRepoName) } // Test removal of multiple repos in one go var testRepoNames = []string{"foo", "bar", "baz"} cacheFiles := make(map[string][]string, len(testRepoNames)) // Add test repos for _, repoName := range testRepoNames { o := &repoAddOptions{ name: repoName, url: ts.URL(), repoFile: repoFile, } if err := o.run(os.Stderr); err != nil { t.Error(err) } cacheIndex, cacheChart := createCacheFiles(rootDir, repoName) cacheFiles[repoName] = []string{cacheIndex, cacheChart} } // Create repo remove command multiRmOpts := repoRemoveOptions{ names: testRepoNames, repoFile: repoFile, repoCache: rootDir, } // Reset the buffer before running repo remove b.Reset() // Run repo remove command if err := multiRmOpts.run(b); err != nil { t.Errorf("Error removing list of repos from repositories: %q", testRepoNames) } // Check that stuff were removed if !strings.Contains(b.String(), "has been removed") { t.Errorf("Unexpected output: %s", b.String()) } for _, repoName := range testRepoNames { f, err := repo.LoadFile(repoFile) if err != nil { t.Error(err) } if f.Has(repoName) { t.Errorf("%s was not successfully removed from repositories list", repoName) } cacheIndex := cacheFiles[repoName][0] cacheChart := cacheFiles[repoName][1] testCacheFiles(t, cacheIndex, cacheChart, repoName) } } func createCacheFiles(rootDir string, repoName string) (cacheIndexFile string, cacheChartsFile string) { cacheIndexFile = filepath.Join(rootDir, helmpath.CacheIndexFile(repoName)) mf, _ := os.Create(cacheIndexFile) mf.Close() cacheChartsFile = filepath.Join(rootDir, helmpath.CacheChartsFile(repoName)) mf, _ = os.Create(cacheChartsFile) mf.Close() return cacheIndexFile, cacheChartsFile } func testCacheFiles(t *testing.T, cacheIndexFile string, cacheChartsFile string, repoName string) { t.Helper() if _, err := os.Stat(cacheIndexFile); err == nil { t.Errorf("Error cache index file was not removed for repository %s", repoName) } if _, err := os.Stat(cacheChartsFile); err == nil { t.Errorf("Error cache chart file was not removed for repository %s", repoName) } } func TestRepoRemoveCompletion(t *testing.T) { ts := repotest.NewTempServer( t, repotest.WithChartSourceGlob("testdata/testserver/*.*"), ) defer ts.Stop() rootDir := t.TempDir() repoFile := filepath.Join(rootDir, "repositories.yaml") repoCache := filepath.Join(rootDir, "cache/") var testRepoNames = []string{"foo", "bar", "baz"} // Add test repos for _, repoName := range testRepoNames { o := &repoAddOptions{ name: repoName, url: ts.URL(), repoFile: repoFile, } if err := o.run(os.Stderr); err != nil { t.Error(err) } } repoSetup := fmt.Sprintf("--repository-config %s --repository-cache %s", repoFile, repoCache) // In the following tests, we turn off descriptions for completions by using __completeNoDesc. // We have to do this because the description will contain the port used by the webserver, // and that port changes each time we run the test. tests := []cmdTestCase{{ name: "completion for repo remove", cmd: fmt.Sprintf("%s __completeNoDesc repo remove ''", repoSetup), golden: "output/repo_list_comp.txt", }, { name: "completion for repo remove, no filter", cmd: fmt.Sprintf("%s __completeNoDesc repo remove fo", repoSetup), golden: "output/repo_list_comp.txt", }, { name: "completion for repo remove repetition", cmd: fmt.Sprintf("%s __completeNoDesc repo remove foo ''", repoSetup), golden: "output/repo_repeat_comp.txt", }} for _, test := range tests { runTestCmd(t, []cmdTestCase{test}) } } func TestRepoRemoveFileCompletion(t *testing.T) { checkFileCompletion(t, "repo remove", false) checkFileCompletion(t, "repo remove repo1", false) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/get_notes.go
pkg/cmd/get_notes.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "io" "log" "github.com/spf13/cobra" "helm.sh/helm/v4/pkg/action" "helm.sh/helm/v4/pkg/cmd/require" "helm.sh/helm/v4/pkg/release" ) var getNotesHelp = ` This command shows notes provided by the chart of a named release. ` func newGetNotesCmd(cfg *action.Configuration, out io.Writer) *cobra.Command { client := action.NewGet(cfg) cmd := &cobra.Command{ Use: "notes RELEASE_NAME", Short: "download the notes for a named release", Long: getNotesHelp, Args: require.ExactArgs(1), ValidArgsFunction: func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { if len(args) != 0 { return noMoreArgsComp() } return compListReleases(toComplete, args, cfg) }, RunE: func(_ *cobra.Command, args []string) error { res, err := client.Run(args[0]) if err != nil { return err } rac, err := release.NewAccessor(res) if err != nil { return err } if len(rac.Notes()) > 0 { fmt.Fprintf(out, "NOTES:\n%s\n", rac.Notes()) } return nil }, } f := cmd.Flags() f.IntVar(&client.Version, "revision", 0, "get the named release with revision") err := cmd.RegisterFlagCompletionFunc("revision", func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { if len(args) == 1 { return compListRevisions(toComplete, cfg, args[0]) } return nil, cobra.ShellCompDirectiveNoFileComp }) if err != nil { log.Fatal(err) } return cmd }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/package.go
pkg/cmd/package.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "errors" "fmt" "io" "os" "path/filepath" "github.com/spf13/cobra" "helm.sh/helm/v4/pkg/action" "helm.sh/helm/v4/pkg/cli/values" "helm.sh/helm/v4/pkg/downloader" "helm.sh/helm/v4/pkg/getter" ) const packageDesc = ` This command packages a chart into a versioned chart archive file. If a path is given, this will look at that path for a chart (which must contain a Chart.yaml file) and then package that directory. Versioned chart archives are used by Helm package repositories. To sign a chart, use the '--sign' flag. In most cases, you should also provide '--keyring path/to/secret/keys' and '--key keyname'. $ helm package --sign ./mychart --key mykey --keyring ~/.gnupg/secring.gpg If '--keyring' is not specified, Helm usually defaults to the public keyring unless your environment is otherwise configured. ` func newPackageCmd(out io.Writer) *cobra.Command { client := action.NewPackage() valueOpts := &values.Options{} cmd := &cobra.Command{ Use: "package [CHART_PATH] [...]", Short: "package a chart directory into a chart archive", Long: packageDesc, RunE: func(_ *cobra.Command, args []string) error { if len(args) == 0 { return fmt.Errorf("need at least one argument, the path to the chart") } if client.Sign { if client.Key == "" { return errors.New("--key is required for signing a package") } if client.Keyring == "" { return errors.New("--keyring is required for signing a package") } } client.RepositoryConfig = settings.RepositoryConfig client.RepositoryCache = settings.RepositoryCache p := getter.All(settings) vals, err := valueOpts.MergeValues(p) if err != nil { return err } registryClient, err := newRegistryClient(client.CertFile, client.KeyFile, client.CaFile, client.InsecureSkipTLSVerify, client.PlainHTTP, client.Username, client.Password) if err != nil { return fmt.Errorf("missing registry client: %w", err) } for i := range args { path, err := filepath.Abs(args[i]) if err != nil { return err } if _, err := os.Stat(args[i]); err != nil { return err } if client.DependencyUpdate { downloadManager := &downloader.Manager{ Out: io.Discard, ChartPath: path, Keyring: client.Keyring, Getters: p, Debug: settings.Debug, RegistryClient: registryClient, RepositoryConfig: settings.RepositoryConfig, RepositoryCache: settings.RepositoryCache, ContentCache: settings.ContentCache, } if err := downloadManager.Update(); err != nil { return err } } p, err := client.Run(path, vals) if err != nil { return err } fmt.Fprintf(out, "Successfully packaged chart and saved it to: %s\n", p) } return nil }, } f := cmd.Flags() f.BoolVar(&client.Sign, "sign", false, "use a PGP private key to sign this package") f.StringVar(&client.Key, "key", "", "name of the key to use when signing. Used if --sign is true") f.StringVar(&client.Keyring, "keyring", defaultKeyring(), "location of a public keyring") f.StringVar(&client.PassphraseFile, "passphrase-file", "", `location of a file which contains the passphrase for the signing key. Use "-" in order to read from stdin.`) f.StringVar(&client.Version, "version", "", "set the version on the chart to this semver version") f.StringVar(&client.AppVersion, "app-version", "", "set the appVersion on the chart to this version") f.StringVarP(&client.Destination, "destination", "d", ".", "location to write the chart.") f.BoolVarP(&client.DependencyUpdate, "dependency-update", "u", false, `update dependencies from "Chart.yaml" to dir "charts/" before packaging`) f.StringVar(&client.Username, "username", "", "chart repository username where to locate the requested chart") f.StringVar(&client.Password, "password", "", "chart repository password where to locate the requested chart") f.StringVar(&client.CertFile, "cert-file", "", "identify HTTPS client using this SSL certificate file") f.StringVar(&client.KeyFile, "key-file", "", "identify HTTPS client using this SSL key file") f.BoolVar(&client.InsecureSkipTLSVerify, "insecure-skip-tls-verify", false, "skip tls certificate checks for the chart download") f.BoolVar(&client.PlainHTTP, "plain-http", false, "use insecure HTTP connections for the chart download") f.StringVar(&client.CaFile, "ca-file", "", "verify certificates of HTTPS-enabled servers using this CA bundle") return cmd }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/helpers.go
pkg/cmd/helpers.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "log/slog" "strconv" "github.com/spf13/cobra" "helm.sh/helm/v4/pkg/action" ) func addDryRunFlag(cmd *cobra.Command) { // --dry-run options with expected outcome: // - Not set means no dry run and server is contacted. // - Set with no value, a value of client, or a value of true and the server is not contacted // - Set with a value of false, none, or false and the server is contacted // The true/false part is meant to reflect some legacy behavior while none is equal to "". f := cmd.Flags() f.String( "dry-run", "none", `simulates the operation without persisting changes. Must be one of: "none" (default), "client", or "server". '--dry-run=none' executes the operation normally and persists changes (no simulation). '--dry-run=client' simulates the operation client-side only and avoids cluster connections. '--dry-run=server' simulates the operation on the server, requiring cluster connectivity.`) f.Lookup("dry-run").NoOptDefVal = "unset" } // Determine the `action.DryRunStrategy` given -dry-run=<value>` flag (or absence of) // Legacy usage of the flag: boolean values, and `--dry-run` (without value) are supported, and log warnings emitted func cmdGetDryRunFlagStrategy(cmd *cobra.Command, isTemplate bool) (action.DryRunStrategy, error) { f := cmd.Flag("dry-run") v := f.Value.String() switch v { case f.NoOptDefVal: slog.Warn(`--dry-run is deprecated and should be replaced with '--dry-run=client'`) return action.DryRunClient, nil case string(action.DryRunClient): return action.DryRunClient, nil case string(action.DryRunServer): return action.DryRunServer, nil case string(action.DryRunNone): if isTemplate { // Special case hack for `helm template`, which is always a dry run return action.DryRunNone, fmt.Errorf(`invalid dry-run value (%q). Must be "server" or "client"`, v) } return action.DryRunNone, nil } b, err := strconv.ParseBool(v) if err != nil { return action.DryRunNone, fmt.Errorf(`invalid dry-run value (%q). Must be "none", "server", or "client"`, v) } if isTemplate && !b { // Special case for `helm template`, which is always a dry run return action.DryRunNone, fmt.Errorf(`invalid dry-run value (%q). Must be "server" or "client"`, v) } result := action.DryRunNone if b { result = action.DryRunClient } slog.Warn(fmt.Sprintf(`boolean '--dry-run=%v' flag is deprecated and must be replaced with '--dry-run=%s'`, v, result)) return result, nil }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/dependency_update.go
pkg/cmd/dependency_update.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "io" "path/filepath" "github.com/spf13/cobra" "helm.sh/helm/v4/pkg/action" "helm.sh/helm/v4/pkg/cmd/require" "helm.sh/helm/v4/pkg/downloader" "helm.sh/helm/v4/pkg/getter" ) const dependencyUpDesc = ` Update the on-disk dependencies to mirror Chart.yaml. This command verifies that the required charts, as expressed in 'Chart.yaml', are present in 'charts/' and are at an acceptable version. It will pull down the latest charts that satisfy the dependencies, and clean up old dependencies. On successful update, this will generate a lock file that can be used to rebuild the dependencies to an exact version. Dependencies are not required to be represented in 'Chart.yaml'. For that reason, an update command will not remove charts unless they are (a) present in the Chart.yaml file, but (b) at the wrong version. ` // newDependencyUpdateCmd creates a new dependency update command. func newDependencyUpdateCmd(_ *action.Configuration, out io.Writer) *cobra.Command { client := action.NewDependency() cmd := &cobra.Command{ Use: "update CHART", Aliases: []string{"up"}, Short: "update charts/ based on the contents of Chart.yaml", Long: dependencyUpDesc, Args: require.MaximumNArgs(1), RunE: func(_ *cobra.Command, args []string) error { chartpath := "." if len(args) > 0 { chartpath = filepath.Clean(args[0]) } registryClient, err := newRegistryClient(client.CertFile, client.KeyFile, client.CaFile, client.InsecureSkipTLSVerify, client.PlainHTTP, client.Username, client.Password) if err != nil { return fmt.Errorf("missing registry client: %w", err) } man := &downloader.Manager{ Out: out, ChartPath: chartpath, Keyring: client.Keyring, SkipUpdate: client.SkipRefresh, Getters: getter.All(settings), RegistryClient: registryClient, RepositoryConfig: settings.RepositoryConfig, RepositoryCache: settings.RepositoryCache, ContentCache: settings.ContentCache, Debug: settings.Debug, } if client.Verify { man.Verify = downloader.VerifyAlways } return man.Update() }, } f := cmd.Flags() addDependencySubcommandFlags(f, client) return cmd }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/dependency_test.go
pkg/cmd/dependency_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "runtime" "testing" ) func TestDependencyListCmd(t *testing.T) { noSuchChart := cmdTestCase{ name: "No such chart", cmd: "dependency list /no/such/chart", golden: "output/dependency-list-no-chart-linux.txt", wantError: true, } noDependencies := cmdTestCase{ name: "No dependencies", cmd: "dependency list testdata/testcharts/alpine", golden: "output/dependency-list-no-requirements-linux.txt", } if runtime.GOOS == "windows" { noSuchChart.golden = "output/dependency-list-no-chart-windows.txt" noDependencies.golden = "output/dependency-list-no-requirements-windows.txt" } tests := []cmdTestCase{noSuchChart, noDependencies, { name: "Dependencies in chart dir", cmd: "dependency list testdata/testcharts/reqtest", golden: "output/dependency-list.txt", }, { name: "Dependencies in chart archive", cmd: "dependency list testdata/testcharts/reqtest-0.1.0.tgz", golden: "output/dependency-list-archive.txt", }} runTestCmd(t, tests) } func TestDependencyFileCompletion(t *testing.T) { checkFileCompletion(t, "dependency", false) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/registry_logout_test.go
pkg/cmd/registry_logout_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "testing" ) func TestRegistryLogoutFileCompletion(t *testing.T) { checkFileCompletion(t, "registry logout", false) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/upgrade.go
pkg/cmd/upgrade.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "context" "fmt" "io" "log" "log/slog" "os" "os/signal" "syscall" "time" "github.com/spf13/cobra" "helm.sh/helm/v4/pkg/action" ci "helm.sh/helm/v4/pkg/chart" "helm.sh/helm/v4/pkg/chart/loader" "helm.sh/helm/v4/pkg/cli/output" "helm.sh/helm/v4/pkg/cli/values" "helm.sh/helm/v4/pkg/cmd/require" "helm.sh/helm/v4/pkg/downloader" "helm.sh/helm/v4/pkg/getter" ri "helm.sh/helm/v4/pkg/release" "helm.sh/helm/v4/pkg/release/common" "helm.sh/helm/v4/pkg/storage/driver" ) const upgradeDesc = ` This command upgrades a release to a new version of a chart. The upgrade arguments must be a release and chart. The chart argument can be either: a chart reference('example/mariadb'), a path to a chart directory, a packaged chart, or a fully qualified URL. For chart references, the latest version will be specified unless the '--version' flag is set. To override values in a chart, use either the '--values' flag and pass in a file or use the '--set' flag and pass configuration from the command line, to force string values, use '--set-string'. You can use '--set-file' to set individual values from a file when the value itself is too long for the command line or is dynamically generated. You can also use '--set-json' to set json values (scalars/objects/arrays) from the command line. Additionally, you can use '--set-json' and passing json object as a string. You can specify the '--values'/'-f' flag multiple times. The priority will be given to the last (right-most) file specified. For example, if both myvalues.yaml and override.yaml contained a key called 'Test', the value set in override.yaml would take precedence: $ helm upgrade -f myvalues.yaml -f override.yaml redis ./redis You can specify the '--set' flag multiple times. The priority will be given to the last (right-most) set specified. For example, if both 'bar' and 'newbar' values are set for a key called 'foo', the 'newbar' value would take precedence: $ helm upgrade --set foo=bar --set foo=newbar redis ./redis You can update the values for an existing release with this command as well via the '--reuse-values' flag. The 'RELEASE' and 'CHART' arguments should be set to the original parameters, and existing values will be merged with any values set via '--values'/'-f' or '--set' flags. Priority is given to new values. $ helm upgrade --reuse-values --set foo=bar --set foo=newbar redis ./redis The --dry-run flag will output all generated chart manifests, including Secrets which can contain sensitive values. To hide Kubernetes Secrets use the --hide-secret flag. Please carefully consider how and when these flags are used. ` func newUpgradeCmd(cfg *action.Configuration, out io.Writer) *cobra.Command { client := action.NewUpgrade(cfg) valueOpts := &values.Options{} var outfmt output.Format var createNamespace bool cmd := &cobra.Command{ Use: "upgrade [RELEASE] [CHART]", Short: "upgrade a release", Long: upgradeDesc, Args: require.ExactArgs(2), ValidArgsFunction: func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { if len(args) == 0 { return compListReleases(toComplete, args, cfg) } if len(args) == 1 { return compListCharts(toComplete, true) } return noMoreArgsComp() }, RunE: func(cmd *cobra.Command, args []string) error { client.Namespace = settings.Namespace() registryClient, err := newRegistryClient(client.CertFile, client.KeyFile, client.CaFile, client.InsecureSkipTLSVerify, client.PlainHTTP, client.Username, client.Password) if err != nil { return fmt.Errorf("missing registry client: %w", err) } client.SetRegistryClient(registryClient) dryRunStrategy, err := cmdGetDryRunFlagStrategy(cmd, false) if err != nil { return err } client.DryRunStrategy = dryRunStrategy // Fixes #7002 - Support reading values from STDIN for `upgrade` command // Must load values AFTER determining if we have to call install so that values loaded from stdin are not read twice if client.Install { // If a release does not exist, install it. histClient := action.NewHistory(cfg) histClient.Max = 1 versions, err := histClient.Run(args[0]) if err == driver.ErrReleaseNotFound || isReleaseUninstalled(versions) { // Only print this to stdout for table output if outfmt == output.Table { fmt.Fprintf(out, "Release %q does not exist. Installing it now.\n", args[0]) } instClient := action.NewInstall(cfg) instClient.CreateNamespace = createNamespace instClient.ChartPathOptions = client.ChartPathOptions instClient.ForceReplace = client.ForceReplace instClient.DryRunStrategy = client.DryRunStrategy instClient.DisableHooks = client.DisableHooks instClient.SkipCRDs = client.SkipCRDs instClient.Timeout = client.Timeout instClient.WaitStrategy = client.WaitStrategy instClient.WaitForJobs = client.WaitForJobs instClient.Devel = client.Devel instClient.Namespace = client.Namespace instClient.RollbackOnFailure = client.RollbackOnFailure instClient.PostRenderer = client.PostRenderer instClient.DisableOpenAPIValidation = client.DisableOpenAPIValidation instClient.SubNotes = client.SubNotes instClient.HideNotes = client.HideNotes instClient.SkipSchemaValidation = client.SkipSchemaValidation instClient.Description = client.Description instClient.DependencyUpdate = client.DependencyUpdate instClient.Labels = client.Labels instClient.EnableDNS = client.EnableDNS instClient.HideSecret = client.HideSecret instClient.TakeOwnership = client.TakeOwnership instClient.ForceConflicts = client.ForceConflicts instClient.ServerSideApply = client.ServerSideApply != "false" if isReleaseUninstalled(versions) { instClient.Replace = true } rel, err := runInstall(args, instClient, valueOpts, out) if err != nil { return err } return outfmt.Write(out, &statusPrinter{ release: rel, debug: settings.Debug, showMetadata: false, hideNotes: instClient.HideNotes, noColor: settings.ShouldDisableColor(), }) } else if err != nil { return err } } if client.Version == "" && client.Devel { slog.Debug("setting version to >0.0.0-0") client.Version = ">0.0.0-0" } chartPath, err := client.LocateChart(args[1], settings) if err != nil { return err } p := getter.All(settings) vals, err := valueOpts.MergeValues(p) if err != nil { return err } // Check chart dependencies to make sure all are present in /charts ch, err := loader.Load(chartPath) if err != nil { return err } ac, err := ci.NewAccessor(ch) if err != nil { return err } if req := ac.MetaDependencies(); len(req) > 0 { if err := action.CheckDependencies(ch, req); err != nil { err = fmt.Errorf("an error occurred while checking for chart dependencies. You may need to run `helm dependency build` to fetch missing dependencies: %w", err) if client.DependencyUpdate { man := &downloader.Manager{ Out: out, ChartPath: chartPath, Keyring: client.Keyring, SkipUpdate: false, Getters: p, RepositoryConfig: settings.RepositoryConfig, RepositoryCache: settings.RepositoryCache, ContentCache: settings.ContentCache, Debug: settings.Debug, } if err := man.Update(); err != nil { return err } // Reload the chart with the updated Chart.lock file. if ch, err = loader.Load(chartPath); err != nil { return fmt.Errorf("failed reloading chart after repo update: %w", err) } } else { return err } } } if ac.Deprecated() { slog.Warn("this chart is deprecated") } // Create context and prepare the handle of SIGTERM ctx := context.Background() ctx, cancel := context.WithCancel(ctx) // Set up channel on which to send signal notifications. // We must use a buffered channel or risk missing the signal // if we're not ready to receive when the signal is sent. cSignal := make(chan os.Signal, 2) signal.Notify(cSignal, os.Interrupt, syscall.SIGTERM) go func() { <-cSignal fmt.Fprintf(out, "Release %s has been cancelled.\n", args[0]) cancel() }() rel, err := client.RunWithContext(ctx, args[0], ch, vals) if err != nil { return fmt.Errorf("UPGRADE FAILED: %w", err) } if outfmt == output.Table { fmt.Fprintf(out, "Release %q has been upgraded. Happy Helming!\n", args[0]) } return outfmt.Write(out, &statusPrinter{ release: rel, debug: settings.Debug, showMetadata: false, hideNotes: client.HideNotes, noColor: settings.ShouldDisableColor(), }) }, } f := cmd.Flags() f.BoolVar(&createNamespace, "create-namespace", false, "if --install is set, create the release namespace if not present") f.BoolVarP(&client.Install, "install", "i", false, "if a release by this name doesn't already exist, run an install") f.BoolVar(&client.Devel, "devel", false, "use development versions, too. Equivalent to version '>0.0.0-0'. If --version is set, this is ignored") f.BoolVar(&client.HideSecret, "hide-secret", false, "hide Kubernetes Secrets when also using the --dry-run flag") f.BoolVar(&client.ForceReplace, "force-replace", false, "force resource updates by replacement") f.BoolVar(&client.ForceReplace, "force", false, "deprecated") f.MarkDeprecated("force", "use --force-replace instead") f.BoolVar(&client.ForceConflicts, "force-conflicts", false, "if set server-side apply will force changes against conflicts") f.StringVar(&client.ServerSideApply, "server-side", "auto", "must be \"true\", \"false\" or \"auto\". Object updates run in the server instead of the client (\"auto\" defaults the value from the previous chart release's method)") f.BoolVar(&client.DisableHooks, "no-hooks", false, "disable pre/post upgrade hooks") 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.SkipCRDs, "skip-crds", false, "if set, no CRDs will be installed when an upgrade is performed with install flag enabled. By default, CRDs are installed if not already present, when an upgrade is performed with install flag enabled") f.DurationVar(&client.Timeout, "timeout", 300*time.Second, "time to wait for any individual Kubernetes operation (like Jobs for hooks)") f.BoolVar(&client.ResetValues, "reset-values", false, "when upgrading, reset the values to the ones built into the chart") f.BoolVar(&client.ReuseValues, "reuse-values", false, "when upgrading, reuse the last release's values and merge in any overrides from the command line via --set and -f. If '--reset-values' is specified, this is ignored") f.BoolVar(&client.ResetThenReuseValues, "reset-then-reuse-values", false, "when upgrading, reset the values to the ones built into the chart, apply the last release's values and merge in any overrides from the command line via --set and -f. If '--reset-values' or '--reuse-values' is specified, this is ignored") f.BoolVar(&client.WaitForJobs, "wait-for-jobs", false, "if set and --wait enabled, will wait until all Jobs have been completed before marking the release as successful. It will wait for as long as --timeout") f.BoolVar(&client.RollbackOnFailure, "rollback-on-failure", false, "if set, Helm will rollback the upgrade to previous success release upon failure. The --wait flag will be defaulted to \"watcher\" if --rollback-on-failure is set") f.BoolVar(&client.RollbackOnFailure, "atomic", false, "deprecated") f.MarkDeprecated("atomic", "use --rollback-on-failure instead") f.IntVar(&client.MaxHistory, "history-max", settings.MaxHistory, "limit the maximum number of revisions saved per release. Use 0 for no limit") f.BoolVar(&client.CleanupOnFail, "cleanup-on-fail", false, "allow deletion of new resources created in this upgrade when upgrade fails") f.BoolVar(&client.SubNotes, "render-subchart-notes", false, "if set, render subchart notes along with the parent") f.BoolVar(&client.HideNotes, "hide-notes", false, "if set, do not show notes in upgrade output. Does not affect presence in chart metadata") f.BoolVar(&client.SkipSchemaValidation, "skip-schema-validation", false, "if set, disables JSON schema validation") f.StringToStringVarP(&client.Labels, "labels", "l", nil, "Labels that would be added to release metadata. Should be separated by comma. Original release labels will be merged with upgrade labels. You can unset label using null.") f.StringVar(&client.Description, "description", "", "add a custom description") f.BoolVar(&client.DependencyUpdate, "dependency-update", false, "update dependencies if they are missing before installing the chart") f.BoolVar(&client.EnableDNS, "enable-dns", false, "enable DNS lookups when rendering templates") f.BoolVar(&client.TakeOwnership, "take-ownership", false, "if set, upgrade will ignore the check for helm annotations and take ownership of the existing resources") addDryRunFlag(cmd) addChartPathOptionsFlags(f, &client.ChartPathOptions) addValueOptionsFlags(f, valueOpts) bindOutputFlag(cmd, &outfmt) bindPostRenderFlag(cmd, &client.PostRenderer, settings) AddWaitFlag(cmd, &client.WaitStrategy) cmd.MarkFlagsMutuallyExclusive("force-replace", "force-conflicts") cmd.MarkFlagsMutuallyExclusive("force", "force-conflicts") err := cmd.RegisterFlagCompletionFunc("version", func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { if len(args) != 2 { return nil, cobra.ShellCompDirectiveNoFileComp } return compVersionFlag(args[1], toComplete) }) if err != nil { log.Fatal(err) } return cmd } func isReleaseUninstalled(versionsi []ri.Releaser) bool { versions, err := releaseListToV1List(versionsi) if err != nil { slog.Error("cannot convert release list to v1 release list", "error", err) return false } return len(versions) > 0 && versions[len(versions)-1].Info.Status == common.StatusUninstalled }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/plugin_uninstall.go
pkg/cmd/plugin_uninstall.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "errors" "fmt" "io" "log/slog" "os" "path/filepath" "github.com/spf13/cobra" "helm.sh/helm/v4/internal/plugin" ) type pluginUninstallOptions struct { names []string } func newPluginUninstallCmd(out io.Writer) *cobra.Command { o := &pluginUninstallOptions{} cmd := &cobra.Command{ Use: "uninstall <plugin>...", Aliases: []string{"rm", "remove"}, Short: "uninstall one or more Helm plugins", ValidArgsFunction: func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return compListPlugins(toComplete, args), cobra.ShellCompDirectiveNoFileComp }, PreRunE: func(_ *cobra.Command, args []string) error { return o.complete(args) }, RunE: func(_ *cobra.Command, _ []string) error { return o.run(out) }, } return cmd } func (o *pluginUninstallOptions) complete(args []string) error { if len(args) == 0 { return errors.New("please provide plugin name to uninstall") } o.names = args return nil } func (o *pluginUninstallOptions) run(out io.Writer) error { slog.Debug("loading installer plugins", "dir", settings.PluginsDirectory) plugins, err := plugin.LoadAll(settings.PluginsDirectory) if err != nil { return err } var errorPlugins []error for _, name := range o.names { if found := findPlugin(plugins, name); found != nil { if err := uninstallPlugin(found); err != nil { errorPlugins = append(errorPlugins, fmt.Errorf("failed to uninstall plugin %s, got error (%v)", name, err)) } else { fmt.Fprintf(out, "Uninstalled plugin: %s\n", name) } } else { errorPlugins = append(errorPlugins, fmt.Errorf("plugin: %s not found", name)) } } if len(errorPlugins) > 0 { return errors.Join(errorPlugins...) } return nil } func uninstallPlugin(p plugin.Plugin) error { if err := os.RemoveAll(p.Dir()); err != nil { return err } // Clean up versioned tarball and provenance files from HELM_PLUGINS directory // These files are saved with pattern: PLUGIN_NAME-VERSION.tgz and PLUGIN_NAME-VERSION.tgz.prov pluginName := p.Metadata().Name pluginVersion := p.Metadata().Version pluginsDir := settings.PluginsDirectory // Remove versioned files: plugin-name-version.tgz and plugin-name-version.tgz.prov if pluginVersion != "" { versionedBasename := fmt.Sprintf("%s-%s.tgz", pluginName, pluginVersion) // Remove tarball file tarballPath := filepath.Join(pluginsDir, versionedBasename) if _, err := os.Stat(tarballPath); err == nil { slog.Debug("removing versioned tarball", "path", tarballPath) if err := os.Remove(tarballPath); err != nil { slog.Debug("failed to remove tarball file", "path", tarballPath, "error", err) } } // Remove provenance file provPath := filepath.Join(pluginsDir, versionedBasename+".prov") if _, err := os.Stat(provPath); err == nil { slog.Debug("removing versioned provenance", "path", provPath) if err := os.Remove(provPath); err != nil { slog.Debug("failed to remove provenance file", "path", provPath, "error", err) } } } return runHook(p, plugin.Delete) } // TODO should this be in pkg/plugin/loader.go? func findPlugin(plugins []plugin.Plugin, name string) plugin.Plugin { for _, p := range plugins { if p.Metadata().Name == name { return p } } return nil }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/push.go
pkg/cmd/push.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "io" "github.com/spf13/cobra" "helm.sh/helm/v4/pkg/action" "helm.sh/helm/v4/pkg/cmd/require" "helm.sh/helm/v4/pkg/pusher" ) const pushDesc = ` Upload a chart to a registry. If the chart has an associated provenance file, it will also be uploaded. ` type registryPushOptions struct { certFile string keyFile string caFile string insecureSkipTLSVerify bool plainHTTP bool password string username string } func newPushCmd(cfg *action.Configuration, out io.Writer) *cobra.Command { o := &registryPushOptions{} cmd := &cobra.Command{ Use: "push [chart] [remote]", Short: "push a chart to remote", Long: pushDesc, Args: require.MinimumNArgs(2), ValidArgsFunction: func(_ *cobra.Command, args []string, _ string) ([]string, cobra.ShellCompDirective) { if len(args) == 0 { // Do file completion for the chart file to push return nil, cobra.ShellCompDirectiveDefault } if len(args) == 1 { providers := []pusher.Provider(pusher.All(settings)) var comps []string for _, p := range providers { for _, scheme := range p.Schemes { comps = append(comps, fmt.Sprintf("%s://", scheme)) } } return comps, cobra.ShellCompDirectiveNoFileComp | cobra.ShellCompDirectiveNoSpace } return noMoreArgsComp() }, RunE: func(_ *cobra.Command, args []string) error { registryClient, err := newRegistryClient( o.certFile, o.keyFile, o.caFile, o.insecureSkipTLSVerify, o.plainHTTP, o.username, o.password, ) if err != nil { return fmt.Errorf("missing registry client: %w", err) } cfg.RegistryClient = registryClient chartRef := args[0] remote := args[1] client := action.NewPushWithOpts(action.WithPushConfig(cfg), action.WithTLSClientConfig(o.certFile, o.keyFile, o.caFile), action.WithInsecureSkipTLSVerify(o.insecureSkipTLSVerify), action.WithPlainHTTP(o.plainHTTP), action.WithPushOptWriter(out)) client.Settings = settings output, err := client.Run(chartRef, remote) if err != nil { return err } fmt.Fprint(out, output) return nil }, } f := cmd.Flags() 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.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.plainHTTP, "plain-http", false, "use insecure HTTP connections for the chart upload") f.StringVar(&o.username, "username", "", "chart repository username where to locate the requested chart") f.StringVar(&o.password, "password", "", "chart repository password where to locate the requested chart") return cmd }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/repo_index_test.go
pkg/cmd/repo_index_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "bytes" "encoding/json" "io" "os" "path/filepath" "testing" "helm.sh/helm/v4/pkg/repo/v1" ) func TestRepoIndexCmd(t *testing.T) { dir := t.TempDir() comp := filepath.Join(dir, "compressedchart-0.1.0.tgz") if err := linkOrCopy("testdata/testcharts/compressedchart-0.1.0.tgz", comp); err != nil { t.Fatal(err) } comp2 := filepath.Join(dir, "compressedchart-0.2.0.tgz") if err := linkOrCopy("testdata/testcharts/compressedchart-0.2.0.tgz", comp2); err != nil { t.Fatal(err) } buf := bytes.NewBuffer(nil) c := newRepoIndexCmd(buf) if err := c.RunE(c, []string{dir}); err != nil { t.Error(err) } destIndex := filepath.Join(dir, "index.yaml") index, err := repo.LoadIndexFile(destIndex) if err != nil { t.Fatal(err) } if len(index.Entries) != 1 { t.Errorf("expected 1 entry, got %d: %#v", len(index.Entries), index.Entries) } vs := index.Entries["compressedchart"] if len(vs) != 2 { t.Errorf("expected 2 versions, got %d: %#v", len(vs), vs) } expectedVersion := "0.2.0" if vs[0].Version != expectedVersion { t.Errorf("expected %q, got %q", expectedVersion, vs[0].Version) } b, err := os.ReadFile(destIndex) if err != nil { t.Fatal(err) } if json.Valid(b) { t.Error("did not expect index file to be valid json") } // Test with `--json` c.ParseFlags([]string{"--json", "true"}) if err := c.RunE(c, []string{dir}); err != nil { t.Error(err) } if b, err = os.ReadFile(destIndex); err != nil { t.Fatal(err) } if !json.Valid(b) { t.Error("index file is not valid json") } // Test with `--merge` // Remove first two charts. if err := os.Remove(comp); err != nil { t.Fatal(err) } if err := os.Remove(comp2); err != nil { t.Fatal(err) } // Add a new chart and a new version of an existing chart if err := linkOrCopy("testdata/testcharts/reqtest-0.1.0.tgz", filepath.Join(dir, "reqtest-0.1.0.tgz")); err != nil { t.Fatal(err) } if err := linkOrCopy("testdata/testcharts/compressedchart-0.3.0.tgz", filepath.Join(dir, "compressedchart-0.3.0.tgz")); err != nil { t.Fatal(err) } c.ParseFlags([]string{"--merge", destIndex}) if err := c.RunE(c, []string{dir}); err != nil { t.Error(err) } index, err = repo.LoadIndexFile(destIndex) if err != nil { t.Fatal(err) } if len(index.Entries) != 2 { t.Errorf("expected 2 entries, got %d: %#v", len(index.Entries), index.Entries) } vs = index.Entries["compressedchart"] if len(vs) != 3 { t.Errorf("expected 3 versions, got %d: %#v", len(vs), vs) } expectedVersion = "0.3.0" if vs[0].Version != expectedVersion { t.Errorf("expected %q, got %q", expectedVersion, vs[0].Version) } // test that index.yaml gets generated on merge even when it doesn't exist if err := os.Remove(destIndex); err != nil { t.Fatal(err) } c.ParseFlags([]string{"--merge", destIndex}) if err := c.RunE(c, []string{dir}); err != nil { t.Error(err) } index, err = repo.LoadIndexFile(destIndex) if err != nil { t.Fatal(err) } // verify it didn't create an empty index.yaml and the merged happened if len(index.Entries) != 2 { t.Errorf("expected 2 entries, got %d: %#v", len(index.Entries), index.Entries) } vs = index.Entries["compressedchart"] if len(vs) != 1 { t.Errorf("expected 1 versions, got %d: %#v", len(vs), vs) } expectedVersion = "0.3.0" if vs[0].Version != expectedVersion { t.Errorf("expected %q, got %q", expectedVersion, vs[0].Version) } } func linkOrCopy(source, target string) error { if err := os.Link(source, target); err != nil { return copyFile(source, target) } return nil } func copyFile(dst, src string) error { i, err := os.Open(dst) if err != nil { return err } defer i.Close() o, err := os.Create(src) if err != nil { return err } defer o.Close() _, err = io.Copy(o, i) return err } func TestRepoIndexFileCompletion(t *testing.T) { checkFileCompletion(t, "repo index", true) checkFileCompletion(t, "repo index mydir", false) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/search/search.go
pkg/cmd/search/search.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Package search provides client-side repository searching. This supports building an in-memory search index based on the contents of multiple repositories, and then using string matching or regular expressions to find matches. */ package search import ( "path" "regexp" "sort" "strings" "github.com/Masterminds/semver/v3" "helm.sh/helm/v4/pkg/repo/v1" ) // Result is a search result. // // Score indicates how close it is to match. The higher the score, the longer // the distance. type Result struct { Name string Score int Chart *repo.ChartVersion } // Index is a searchable index of chart information. type Index struct { lines map[string]string charts map[string]*repo.ChartVersion } const sep = "\v" // NewIndex creates a new Index. func NewIndex() *Index { return &Index{lines: map[string]string{}, charts: map[string]*repo.ChartVersion{}} } // verSep is a separator for version fields in map keys. const verSep = "$$" // AddRepo adds a repository index to the search index. func (i *Index) AddRepo(rname string, ind *repo.IndexFile, all bool) { ind.SortEntries() for name, ref := range ind.Entries { if len(ref) == 0 { // Skip chart names that have zero releases. continue } // By convention, an index file is supposed to have the newest at the // 0 slot, so our best bet is to grab the 0 entry and build the index // entry off of that. // Note: Do not use filePath.Join since on Windows it will return \ // which results in a repo name that cannot be understood. fname := path.Join(rname, name) if !all { i.lines[fname] = indstr(rname, ref[0]) i.charts[fname] = ref[0] continue } // If 'all' is set, then we go through all of the refs, and add them all // to the index. This will generate a lot of near-duplicate entries. for _, rr := range ref { versionedName := fname + verSep + rr.Version i.lines[versionedName] = indstr(rname, rr) i.charts[versionedName] = rr } } } // All returns all charts in the index as if they were search results. // // Each will be given a score of 0. func (i *Index) All() []*Result { res := make([]*Result, len(i.charts)) j := 0 for name, ch := range i.charts { parts := strings.Split(name, verSep) res[j] = &Result{ Name: parts[0], Chart: ch, } j++ } return res } // Search searches an index for the given term. // // Threshold indicates the maximum score a term may have before being marked // irrelevant. (Low score means higher relevance. Golf, not bowling.) // // If regexp is true, the term is treated as a regular expression. Otherwise, // term is treated as a literal string. func (i *Index) Search(term string, threshold int, regexp bool) ([]*Result, error) { if regexp { return i.SearchRegexp(term, threshold) } return i.SearchLiteral(term, threshold), nil } // calcScore calculates a score for a match. func (i *Index) calcScore(index int, matchline string) int { // This is currently tied to the fact that sep is a single char. splits := []int{} s := rune(sep[0]) for i, ch := range matchline { if ch == s { splits = append(splits, i) } } for i, pos := range splits { if index > pos { continue } return i } return len(splits) } // SearchLiteral does a literal string search (no regexp). func (i *Index) SearchLiteral(term string, threshold int) []*Result { term = strings.ToLower(term) buf := []*Result{} for k, v := range i.lines { lv := strings.ToLower(v) res := strings.Index(lv, term) if score := i.calcScore(res, lv); res != -1 && score < threshold { parts := strings.Split(k, verSep) // Remove version, if it is there. buf = append(buf, &Result{Name: parts[0], Score: score, Chart: i.charts[k]}) } } return buf } // SearchRegexp searches using a regular expression. func (i *Index) SearchRegexp(re string, threshold int) ([]*Result, error) { matcher, err := regexp.Compile(re) if err != nil { return []*Result{}, err } buf := []*Result{} for k, v := range i.lines { ind := matcher.FindStringIndex(v) if len(ind) == 0 { continue } if score := i.calcScore(ind[0], v); ind[0] >= 0 && score < threshold { parts := strings.Split(k, verSep) // Remove version, if it is there. buf = append(buf, &Result{Name: parts[0], Score: score, Chart: i.charts[k]}) } } return buf, nil } // SortScore does an in-place sort of the results. // // Lowest scores are highest on the list. Matching scores are subsorted alphabetically. func SortScore(r []*Result) { sort.Sort(scoreSorter(r)) } // scoreSorter sorts results by score, and subsorts by alpha Name. type scoreSorter []*Result // Len returns the length of this scoreSorter. func (s scoreSorter) Len() int { return len(s) } // Swap performs an in-place swap. func (s scoreSorter) Swap(i, j int) { s[i], s[j] = s[j], s[i] } // Less compares a to b, and returns true if a is less than b. func (s scoreSorter) Less(a, b int) bool { first := s[a] second := s[b] if first.Score > second.Score { return false } if first.Score < second.Score { return true } if first.Name == second.Name { v1, err := semver.NewVersion(first.Chart.Version) if err != nil { return true } v2, err := semver.NewVersion(second.Chart.Version) if err != nil { return true } // Sort so that the newest chart is higher than the oldest chart. This is // the opposite of what you'd expect in a function called Less. return v1.GreaterThan(v2) } return first.Name < second.Name } func indstr(name string, ref *repo.ChartVersion) string { i := ref.Name + sep + name + "/" + ref.Name + sep + ref.Description + sep + strings.Join(ref.Keywords, " ") return i }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/search/search_test.go
pkg/cmd/search/search_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package search import ( "strings" "testing" chart "helm.sh/helm/v4/pkg/chart/v2" "helm.sh/helm/v4/pkg/repo/v1" ) func TestSortScore(t *testing.T) { in := []*Result{ {Name: "bbb", Score: 0, Chart: &repo.ChartVersion{Metadata: &chart.Metadata{Version: "1.2.3"}}}, {Name: "aaa", Score: 5}, {Name: "abb", Score: 5}, {Name: "aab", Score: 0}, {Name: "bab", Score: 5}, {Name: "ver", Score: 5, Chart: &repo.ChartVersion{Metadata: &chart.Metadata{Version: "1.2.4"}}}, {Name: "ver", Score: 5, Chart: &repo.ChartVersion{Metadata: &chart.Metadata{Version: "1.2.3"}}}, } expect := []string{"aab", "bbb", "aaa", "abb", "bab", "ver", "ver"} expectScore := []int{0, 0, 5, 5, 5, 5, 5} SortScore(in) // Test Score for i := range expectScore { if expectScore[i] != in[i].Score { t.Errorf("Sort error on index %d: expected %d, got %d", i, expectScore[i], in[i].Score) } } // Test Name for i := range expect { if expect[i] != in[i].Name { t.Errorf("Sort error: expected %s, got %s", expect[i], in[i].Name) } } // Test version of last two items if in[5].Chart.Version != "1.2.4" { t.Errorf("Expected 1.2.4, got %s", in[5].Chart.Version) } if in[6].Chart.Version != "1.2.3" { t.Error("Expected 1.2.3 to be last") } } var indexfileEntries = map[string]repo.ChartVersions{ "niña": { { URLs: []string{"http://example.com/charts/nina-0.1.0.tgz"}, Metadata: &chart.Metadata{ Name: "niña", Version: "0.1.0", Description: "One boat", }, }, }, "pinta": { { URLs: []string{"http://example.com/charts/pinta-0.1.0.tgz"}, Metadata: &chart.Metadata{ Name: "pinta", Version: "0.1.0", Description: "Two ship", }, }, }, "santa-maria": { { URLs: []string{"http://example.com/charts/santa-maria-1.2.3.tgz"}, Metadata: &chart.Metadata{ Name: "santa-maria", Version: "1.2.3", Description: "Three boat", }, }, { URLs: []string{"http://example.com/charts/santa-maria-1.2.2-rc-1.tgz"}, Metadata: &chart.Metadata{ Name: "santa-maria", Version: "1.2.2-RC-1", Description: "Three boat", }, }, }, } func loadTestIndex(_ *testing.T, all bool) *Index { i := NewIndex() i.AddRepo("testing", &repo.IndexFile{Entries: indexfileEntries}, all) i.AddRepo("ztesting", &repo.IndexFile{Entries: map[string]repo.ChartVersions{ "Pinta": { { URLs: []string{"http://example.com/charts/pinta-2.0.0.tgz"}, Metadata: &chart.Metadata{ Name: "Pinta", Version: "2.0.0", Description: "Two ship, version two", }, }, }, }}, all) return i } func TestAll(t *testing.T) { i := loadTestIndex(t, false) all := i.All() if len(all) != 4 { t.Errorf("Expected 4 entries, got %d", len(all)) } i = loadTestIndex(t, true) all = i.All() if len(all) != 5 { t.Errorf("Expected 5 entries, got %d", len(all)) } } func TestAddRepo_Sort(t *testing.T) { i := loadTestIndex(t, true) sr, err := i.Search("TESTING/SANTA-MARIA", 100, false) if err != nil { t.Fatal(err) } SortScore(sr) ch := sr[0] expect := "1.2.3" if ch.Chart.Version != expect { t.Errorf("Expected %q, got %q", expect, ch.Chart.Version) } } func TestSearchByName(t *testing.T) { tests := []struct { name string query string expect []*Result regexp bool fail bool failMsg string }{ { name: "basic search for one result", query: "santa-maria", expect: []*Result{ {Name: "testing/santa-maria"}, }, }, { name: "basic search for two results", query: "pinta", expect: []*Result{ {Name: "testing/pinta"}, {Name: "ztesting/Pinta"}, }, }, { name: "repo-specific search for one result", query: "ztesting/pinta", expect: []*Result{ {Name: "ztesting/Pinta"}, }, }, { name: "partial name search", query: "santa", expect: []*Result{ {Name: "testing/santa-maria"}, }, }, { name: "description search, one result", query: "Three", expect: []*Result{ {Name: "testing/santa-maria"}, }, }, { name: "description search, two results", query: "two", expect: []*Result{ {Name: "testing/pinta"}, {Name: "ztesting/Pinta"}, }, }, { name: "search mixedCase and result should be mixedCase too", query: "pinta", expect: []*Result{ {Name: "testing/pinta"}, {Name: "ztesting/Pinta"}, }, }, { name: "description upper search, two results", query: "TWO", expect: []*Result{ {Name: "testing/pinta"}, {Name: "ztesting/Pinta"}, }, }, { name: "nothing found", query: "mayflower", expect: []*Result{}, }, { name: "regexp, one result", query: "Th[ref]*", expect: []*Result{ {Name: "testing/santa-maria"}, }, regexp: true, }, { name: "regexp, fail compile", query: "th[", expect: []*Result{}, regexp: true, fail: true, failMsg: "error parsing regexp:", }, } i := loadTestIndex(t, false) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { charts, err := i.Search(tt.query, 100, tt.regexp) if err != nil { if tt.fail { if !strings.Contains(err.Error(), tt.failMsg) { t.Fatalf("Unexpected error message: %s", err) } return } t.Fatalf("%s: %s", tt.name, err) } // Give us predictably ordered results. SortScore(charts) l := len(charts) if l != len(tt.expect) { t.Fatalf("Expected %d result, got %d", len(tt.expect), l) } // For empty result sets, just keep going. if l == 0 { return } for i, got := range charts { ex := tt.expect[i] if got.Name != ex.Name { t.Errorf("[%d]: Expected name %q, got %q", i, ex.Name, got.Name) } } }) } } func TestSearchByNameAll(t *testing.T) { // Test with the All bit turned on. i := loadTestIndex(t, true) cs, err := i.Search("santa-maria", 100, false) if err != nil { t.Fatal(err) } if len(cs) != 2 { t.Errorf("expected 2 charts, got %d", len(cs)) } } func TestCalcScore(t *testing.T) { i := NewIndex() fields := []string{"aaa", "bbb", "ccc", "ddd"} matchline := strings.Join(fields, sep) if r := i.calcScore(2, matchline); r != 0 { t.Errorf("Expected 0, got %d", r) } if r := i.calcScore(5, matchline); r != 1 { t.Errorf("Expected 1, got %d", r) } if r := i.calcScore(10, matchline); r != 2 { t.Errorf("Expected 2, got %d", r) } if r := i.calcScore(14, matchline); r != 3 { t.Errorf("Expected 3, got %d", r) } }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/require/args_test.go
pkg/cmd/require/args_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package require import ( "fmt" "io" "strings" "testing" "github.com/spf13/cobra" ) func TestArgs(t *testing.T) { runTestCases(t, []testCase{{ validateFunc: NoArgs, }, { args: []string{"one"}, validateFunc: NoArgs, wantError: `"root" accepts no arguments`, }, { args: []string{"one"}, validateFunc: ExactArgs(1), }, { validateFunc: ExactArgs(1), wantError: `"root" requires 1 argument`, }, { validateFunc: ExactArgs(2), wantError: `"root" requires 2 arguments`, }, { args: []string{"one"}, validateFunc: MaximumNArgs(1), }, { args: []string{"one", "two"}, validateFunc: MaximumNArgs(1), wantError: `"root" accepts at most 1 argument`, }, { validateFunc: MinimumNArgs(1), wantError: `"root" requires at least 1 argument`, }, { args: []string{"one", "two"}, validateFunc: MinimumNArgs(1), }}) } type testCase struct { args []string validateFunc cobra.PositionalArgs wantError string } func runTestCases(t *testing.T, testCases []testCase) { t.Helper() for i, tc := range testCases { t.Run(fmt.Sprint(i), func(t *testing.T) { cmd := &cobra.Command{ Use: "root", Run: func(*cobra.Command, []string) {}, Args: tc.validateFunc, } cmd.SetArgs(tc.args) cmd.SetOut(io.Discard) cmd.SetErr(io.Discard) err := cmd.Execute() if tc.wantError == "" { if err != nil { t.Fatalf("unexpected error, got '%v'", err) } return } if !strings.Contains(err.Error(), tc.wantError) { t.Fatalf("unexpected error \n\nWANT:\n%q\n\nGOT:\n%q\n", tc.wantError, err) } if !strings.Contains(err.Error(), "Usage:") { t.Fatalf("unexpected error: want Usage string\n\nGOT:\n%q\n", err) } }) } }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/require/args.go
pkg/cmd/require/args.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package require import ( "fmt" "github.com/spf13/cobra" ) // NoArgs returns an error if any args are included. func NoArgs(cmd *cobra.Command, args []string) error { if len(args) > 0 { return fmt.Errorf( "%q accepts no arguments\n\nUsage: %s", cmd.CommandPath(), cmd.UseLine(), ) } return nil } // ExactArgs returns an error if there are not exactly n args. func ExactArgs(n int) cobra.PositionalArgs { return func(cmd *cobra.Command, args []string) error { if len(args) != n { return fmt.Errorf( "%q requires %d %s\n\nUsage: %s", cmd.CommandPath(), n, pluralize("argument", n), cmd.UseLine(), ) } return nil } } // MaximumNArgs returns an error if there are more than N args. func MaximumNArgs(n int) cobra.PositionalArgs { return func(cmd *cobra.Command, args []string) error { if len(args) > n { return fmt.Errorf( "%q accepts at most %d %s\n\nUsage: %s", cmd.CommandPath(), n, pluralize("argument", n), cmd.UseLine(), ) } return nil } } // MinimumNArgs returns an error if there is not at least N args. func MinimumNArgs(n int) cobra.PositionalArgs { return func(cmd *cobra.Command, args []string) error { if len(args) < n { return fmt.Errorf( "%q requires at least %d %s\n\nUsage: %s", cmd.CommandPath(), n, pluralize("argument", n), cmd.UseLine(), ) } return nil } } func pluralize(word string, n int) string { if n == 1 { return word } return word + "s" }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/provenance/sign.go
pkg/provenance/sign.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package provenance import ( "bytes" "crypto" "encoding/hex" "errors" "fmt" "io" "os" "strings" "github.com/ProtonMail/go-crypto/openpgp" //nolint "github.com/ProtonMail/go-crypto/openpgp/clearsign" //nolint "github.com/ProtonMail/go-crypto/openpgp/packet" //nolint "sigs.k8s.io/yaml" ) var defaultPGPConfig = packet.Config{ DefaultHash: crypto.SHA512, } // SumCollection represents a collection of file and image checksums. // // Files are of the form: // // FILENAME: "sha256:SUM" // // Images are of the form: // // "IMAGE:TAG": "sha256:SUM" // // Docker optionally supports sha512, and if this is the case, the hash marker // will be 'sha512' instead of 'sha256'. type SumCollection struct { Files map[string]string `json:"files"` Images map[string]string `json:"images,omitempty"` } // Verification contains information about a verification operation. type Verification struct { // SignedBy contains the entity that signed a package. SignedBy *openpgp.Entity // FileHash is the hash, prepended with the scheme, for the file that was verified. FileHash string // FileName is the name of the file that FileHash verifies. FileName string } // Signatory signs things. // // Signatories can be constructed from a PGP private key file using NewFromFiles, // or they can be constructed manually by setting the Entity to a valid // PGP entity. // // The same Signatory can be used to sign or validate multiple packages. type Signatory struct { // The signatory for this instance of Helm. This is used for signing. Entity *openpgp.Entity // The keyring for this instance of Helm. This is used for verification. KeyRing openpgp.EntityList } // NewFromFiles constructs a new Signatory from the PGP key in the given filename. // // This will emit an error if it cannot find a valid GPG keyfile (entity) at the // given location. // // Note that the keyfile may have just a public key, just a private key, or // both. The Signatory methods may have different requirements of the keys. For // example, ClearSign must have a valid `openpgp.Entity.PrivateKey` before it // can sign something. func NewFromFiles(keyfile, keyringfile string) (*Signatory, error) { e, err := loadKey(keyfile) if err != nil { return nil, err } ring, err := loadKeyRing(keyringfile) if err != nil { return nil, err } return &Signatory{ Entity: e, KeyRing: ring, }, nil } // NewFromKeyring reads a keyring file and creates a Signatory. // // If id is not the empty string, this will also try to find an Entity in the // keyring whose name matches, and set that as the signing entity. It will return // an error if the id is not empty and also not found. func NewFromKeyring(keyringfile, id string) (*Signatory, error) { ring, err := loadKeyRing(keyringfile) if err != nil { return nil, err } s := &Signatory{KeyRing: ring} // If the ID is empty, we can return now. if id == "" { return s, nil } // We're gonna go all GnuPG on this and look for a string that _contains_. If // two or more keys contain the string and none are a direct match, we error // out. var candidate *openpgp.Entity vague := false for _, e := range ring { for n := range e.Identities { if n == id { s.Entity = e return s, nil } if strings.Contains(n, id) { if candidate != nil { vague = true } candidate = e } } } if vague { return s, fmt.Errorf("more than one key contain the id %q", id) } s.Entity = candidate return s, nil } // PassphraseFetcher returns a passphrase for decrypting keys. // // This is used as a callback to read a passphrase from some other location. The // given name is the Name field on the key, typically of the form: // // USER_NAME (COMMENT) <EMAIL> type PassphraseFetcher func(name string) ([]byte, error) // DecryptKey decrypts a private key in the Signatory. // // If the key is not encrypted, this will return without error. // // If the key does not exist, this will return an error. // // If the key exists, but cannot be unlocked with the passphrase returned by // the PassphraseFetcher, this will return an error. // // If the key is successfully unlocked, it will return nil. func (s *Signatory) DecryptKey(fn PassphraseFetcher) error { if s.Entity == nil { return errors.New("private key not found") } else if s.Entity.PrivateKey == nil { return errors.New("provided key is not a private key. Try providing a keyring with secret keys") } // Nothing else to do if key is not encrypted. if !s.Entity.PrivateKey.Encrypted { return nil } fname := "Unknown" for i := range s.Entity.Identities { if i != "" { fname = i break } } p, err := fn(fname) if err != nil { return err } return s.Entity.PrivateKey.Decrypt(p) } // ClearSign signs package data with the given key and pre-marshalled metadata. // // This is the core signing method that works with data in memory. // The Signatory must have a valid Entity.PrivateKey for this to work. func (s *Signatory) ClearSign(archiveData []byte, filename string, metadataBytes []byte) (string, error) { if s.Entity == nil { return "", errors.New("private key not found") } else if s.Entity.PrivateKey == nil { return "", errors.New("provided key is not a private key. Try providing a keyring with secret keys") } out := bytes.NewBuffer(nil) b, err := messageBlock(archiveData, filename, metadataBytes) if err != nil { return "", err } // Sign the buffer w, err := clearsign.Encode(out, s.Entity.PrivateKey, &defaultPGPConfig) if err != nil { return "", err } _, err = io.Copy(w, b) if err != nil { // NB: We intentionally don't call `w.Close()` here! `w.Close()` is the method which // actually does the PGP signing, and therefore is the part which uses the private key. // In other words, if we call Close here, there's a risk that there's an attempt to use the // private key to sign garbage data (since we know that io.Copy failed, `w` won't contain // anything useful). return "", fmt.Errorf("failed to write to clearsign encoder: %w", err) } err = w.Close() if err != nil { return "", fmt.Errorf("failed to either sign or armor message block: %w", err) } return out.String(), nil } // Verify checks a signature and verifies that it is legit for package data. // This is the core verification method that works with data in memory. func (s *Signatory) Verify(archiveData, provData []byte, filename string) (*Verification, error) { ver := &Verification{} // First verify the signature block, _ := clearsign.Decode(provData) if block == nil { return ver, errors.New("signature block not found") } by, err := s.verifySignature(block) if err != nil { return ver, err } ver.SignedBy = by // Second, verify the hash of the data. sum, err := Digest(bytes.NewBuffer(archiveData)) if err != nil { return ver, err } sums, err := parseMessageBlock(block.Plaintext) if err != nil { return ver, err } sum = "sha256:" + sum if sha, ok := sums.Files[filename]; !ok { return ver, fmt.Errorf("provenance does not contain a SHA for a file named %q", filename) } else if sha != sum { return ver, fmt.Errorf("sha256 sum does not match for %s: %q != %q", filename, sha, sum) } ver.FileHash = sum ver.FileName = filename // TODO: when image signing is added, verify that here. return ver, nil } // verifySignature verifies that the given block is validly signed, and returns the signer. func (s *Signatory) verifySignature(block *clearsign.Block) (*openpgp.Entity, error) { return openpgp.CheckDetachedSignature( s.KeyRing, bytes.NewReader(block.Bytes), block.ArmoredSignature.Body, &defaultPGPConfig, ) } // messageBlock creates a message block from archive data and pre-marshalled metadata func messageBlock(archiveData []byte, filename string, metadataBytes []byte) (*bytes.Buffer, error) { // Checksum the archive data chash, err := Digest(bytes.NewBuffer(archiveData)) if err != nil { return nil, err } sums := &SumCollection{ Files: map[string]string{ filename: "sha256:" + chash, }, } // Buffer the metadata + checksums YAML file // FIXME: YAML uses ---\n as a file start indicator, but this is not legal in a PGP // clearsign block. So we use ...\n, which is the YAML document end marker. // http://yaml.org/spec/1.2/spec.html#id2800168 b := bytes.NewBuffer(metadataBytes) b.WriteString("\n...\n") data, err := yaml.Marshal(sums) if err != nil { return nil, err } b.Write(data) return b, nil } // parseMessageBlock parses a message block and returns only checksums (metadata ignored like upstream) func parseMessageBlock(data []byte) (*SumCollection, error) { sc := &SumCollection{} // We ignore metadata, just like upstream - only need checksums for verification if err := ParseMessageBlock(data, nil, sc); err != nil { return sc, err } return sc, nil } // ParseMessageBlock parses a message block containing metadata and checksums. // // This is the generic version that can work with any metadata type. // The metadata parameter should be a pointer to a struct that can be unmarshaled from YAML. func ParseMessageBlock(data []byte, metadata interface{}, sums *SumCollection) error { parts := bytes.Split(data, []byte("\n...\n")) if len(parts) < 2 { return errors.New("message block must have at least two parts") } if metadata != nil { if err := yaml.Unmarshal(parts[0], metadata); err != nil { return err } } return yaml.Unmarshal(parts[1], sums) } // loadKey loads a GPG key found at a particular path. func loadKey(keypath string) (*openpgp.Entity, error) { f, err := os.Open(keypath) if err != nil { return nil, err } defer f.Close() pr := packet.NewReader(f) return openpgp.ReadEntity(pr) } func loadKeyRing(ringpath string) (openpgp.EntityList, error) { f, err := os.Open(ringpath) if err != nil { return nil, err } defer f.Close() return openpgp.ReadKeyRing(f) } // DigestFile calculates a SHA256 hash (like Docker) for a given file. // // It takes the path to the archive file, and returns a string representation of // the SHA256 sum. // // This function can be used to generate a sum of any package archive file. func DigestFile(filename string) (string, error) { f, err := os.Open(filename) if err != nil { return "", err } defer f.Close() return Digest(f) } // Digest hashes a reader and returns a SHA256 digest. // // Helm uses SHA256 as its default hash for all non-cryptographic applications. func Digest(in io.Reader) (string, error) { hash := crypto.SHA256.New() if _, err := io.Copy(hash, in); err != nil { return "", nil } return hex.EncodeToString(hash.Sum(nil)), nil }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/provenance/sign_test.go
pkg/provenance/sign_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package provenance import ( "crypto" "fmt" "io" "os" "path/filepath" "strings" "testing" pgperrors "github.com/ProtonMail/go-crypto/openpgp/errors" //nolint "github.com/ProtonMail/go-crypto/openpgp/packet" //nolint "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "sigs.k8s.io/yaml" "helm.sh/helm/v4/pkg/chart/v2/loader" ) const ( // testKeyFile is the secret key. // Generating keys should be done with `gpg --gen-key`. The current key // was generated to match Go's defaults (RSA/RSA 2048). It has no pass // phrase. Use `gpg --export-secret-keys helm-test` to export the secret. testKeyfile = "testdata/helm-test-key.secret" // testPasswordKeyfile is a keyfile with a password. testPasswordKeyfile = "testdata/helm-password-key.secret" // testPubfile is the public key file. // Use `gpg --export helm-test` to export the public key. testPubfile = "testdata/helm-test-key.pub" // 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>` testPasswordKeyName = `password key (fake) <fake@helm.sh>` testChartfile = "testdata/hashtest-1.2.3.tgz" // testSigBlock points to a signature generated by an external tool. // This file was generated with GnuPG: // gpg --clearsign -u helm-test --openpgp testdata/msgblock.yaml testSigBlock = "testdata/msgblock.yaml.asc" // testTamperedSigBlock is a tampered copy of msgblock.yaml.asc testTamperedSigBlock = "testdata/msgblock.yaml.tampered" // testMixedKeyring points to a keyring containing RSA and ed25519 keys. testMixedKeyring = "testdata/helm-mixed-keyring.pub" // testSumfile points to a SHA256 sum generated by an external tool. // We always want to validate against an external tool's representation to // verify that we haven't done something stupid. This file was generated // with shasum. // shasum -a 256 hashtest-1.2.3.tgz > testdata/hashtest.sha256 testSumfile = "testdata/hashtest.sha256" ) // testMessageBlock represents the expected message block for the testdata/hashtest chart. const testMessageBlock = `apiVersion: v1 description: Test chart versioning name: hashtest version: 1.2.3 ... files: hashtest-1.2.3.tgz: sha256:c6841b3a895f1444a6738b5d04564a57e860ce42f8519c3be807fb6d9bee7888 ` // loadChartMetadataForSigning is a test helper that loads chart metadata and marshals it to YAML bytes func loadChartMetadataForSigning(t *testing.T, chartPath string) []byte { t.Helper() chart, err := loader.LoadFile(chartPath) if err != nil { t.Fatal(err) } metadataBytes, err := yaml.Marshal(chart.Metadata) if err != nil { t.Fatal(err) } return metadataBytes } func TestMessageBlock(t *testing.T) { metadataBytes := loadChartMetadataForSigning(t, testChartfile) // Read the chart file data archiveData, err := os.ReadFile(testChartfile) if err != nil { t.Fatal(err) } out, err := messageBlock(archiveData, filepath.Base(testChartfile), metadataBytes) if err != nil { t.Fatal(err) } got := out.String() if got != testMessageBlock { t.Errorf("Expected:\n%q\nGot\n%q\n", testMessageBlock, got) } } func TestParseMessageBlock(t *testing.T) { sc, err := parseMessageBlock([]byte(testMessageBlock)) if err != nil { t.Fatal(err) } // parseMessageBlock only returns checksums, not metadata (like upstream) if lsc := len(sc.Files); lsc != 1 { t.Errorf("Expected 1 file, got %d", lsc) } if hash, ok := sc.Files["hashtest-1.2.3.tgz"]; !ok { t.Errorf("hashtest file not found in Files") } else if hash != "sha256:c6841b3a895f1444a6738b5d04564a57e860ce42f8519c3be807fb6d9bee7888" { t.Errorf("Unexpected hash: %q", hash) } } func TestLoadKey(t *testing.T) { k, err := loadKey(testKeyfile) if err != nil { t.Fatal(err) } if _, ok := k.Identities[testKeyName]; !ok { t.Errorf("Expected to load a key for user %q", testKeyName) } } func TestLoadKeyRing(t *testing.T) { k, err := loadKeyRing(testPubfile) if err != nil { t.Fatal(err) } if len(k) > 1 { t.Errorf("Expected 1, got %d", len(k)) } for _, e := range k { if ii, ok := e.Identities[testKeyName]; !ok { t.Errorf("Expected %s in %v", testKeyName, ii) } } } func TestDigest(t *testing.T) { f, err := os.Open(testChartfile) if err != nil { t.Fatal(err) } defer f.Close() hash, err := Digest(f) if err != nil { t.Fatal(err) } sig, err := readSumFile(testSumfile) if err != nil { t.Fatal(err) } if !strings.Contains(sig, hash) { t.Errorf("Expected %s to be in %s", hash, sig) } } func TestNewFromFiles(t *testing.T) { s, err := NewFromFiles(testKeyfile, testPubfile) if err != nil { t.Fatal(err) } if _, ok := s.Entity.Identities[testKeyName]; !ok { t.Errorf("Expected to load a key for user %q", testKeyName) } } func TestDigestFile(t *testing.T) { hash, err := DigestFile(testChartfile) if err != nil { t.Fatal(err) } sig, err := readSumFile(testSumfile) if err != nil { t.Fatal(err) } if !strings.Contains(sig, hash) { t.Errorf("Expected %s to be in %s", hash, sig) } } func TestDecryptKey(t *testing.T) { k, err := NewFromKeyring(testPasswordKeyfile, testPasswordKeyName) if err != nil { t.Fatal(err) } if !k.Entity.PrivateKey.Encrypted { t.Fatal("Key is not encrypted") } // We give this a simple callback that returns the password. if err := k.DecryptKey(func(_ string) ([]byte, error) { return []byte("secret"), nil }); err != nil { t.Fatal(err) } // Re-read the key (since we already unlocked it) k, err = NewFromKeyring(testPasswordKeyfile, testPasswordKeyName) if err != nil { t.Fatal(err) } // Now we give it a bogus password. if err := k.DecryptKey(func(_ string) ([]byte, error) { return []byte("secrets_and_lies"), nil }); err == nil { t.Fatal("Expected an error when giving a bogus passphrase") } } func TestClearSign(t *testing.T) { signer, err := NewFromFiles(testKeyfile, testPubfile) if err != nil { t.Fatal(err) } metadataBytes := loadChartMetadataForSigning(t, testChartfile) // Read the chart file data archiveData, err := os.ReadFile(testChartfile) if err != nil { t.Fatal(err) } sig, err := signer.ClearSign(archiveData, filepath.Base(testChartfile), metadataBytes) if err != nil { t.Fatal(err) } t.Logf("Sig:\n%s", sig) if !strings.Contains(sig, testMessageBlock) { t.Errorf("expected message block to be in sig: %s", sig) } } func TestMixedKeyringRSASigningAndVerification(t *testing.T) { signer, err := NewFromFiles(testKeyfile, testMixedKeyring) require.NoError(t, err) require.NotEmpty(t, signer.KeyRing, "expected signer keyring to be loaded") hasEdDSA := false for _, entity := range signer.KeyRing { if entity.PrimaryKey != nil && entity.PrimaryKey.PubKeyAlgo == packet.PubKeyAlgoEdDSA { hasEdDSA = true break } for _, subkey := range entity.Subkeys { if subkey.PublicKey != nil && subkey.PublicKey.PubKeyAlgo == packet.PubKeyAlgoEdDSA { hasEdDSA = true break } } if hasEdDSA { break } } assert.True(t, hasEdDSA, "expected %s to include an Ed25519 public key", testMixedKeyring) require.NotNil(t, signer.Entity, "expected signer entity to be loaded") require.NotNil(t, signer.Entity.PrivateKey, "expected signer private key to be loaded") assert.Equal(t, packet.PubKeyAlgoRSA, signer.Entity.PrivateKey.PubKeyAlgo, "expected RSA key") metadataBytes := loadChartMetadataForSigning(t, testChartfile) archiveData, err := os.ReadFile(testChartfile) require.NoError(t, err) sig, err := signer.ClearSign(archiveData, filepath.Base(testChartfile), metadataBytes) require.NoError(t, err, "failed to sign chart") verification, err := signer.Verify(archiveData, []byte(sig), filepath.Base(testChartfile)) require.NoError(t, err, "failed to verify chart signature") require.NotNil(t, verification.SignedBy, "expected verification to include signer") require.NotNil(t, verification.SignedBy.PrimaryKey, "expected verification to include signer primary key") assert.Equal(t, packet.PubKeyAlgoRSA, verification.SignedBy.PrimaryKey.PubKeyAlgo, "expected verification to report RSA key") _, ok := verification.SignedBy.Identities[testKeyName] assert.True(t, ok, "expected verification to be signed by %q", testKeyName) } // failSigner always fails to sign and returns an error type failSigner struct{} func (s failSigner) Public() crypto.PublicKey { return nil } func (s failSigner) Sign(_ io.Reader, _ []byte, _ crypto.SignerOpts) ([]byte, error) { return nil, fmt.Errorf("always fails") } func TestClearSignError(t *testing.T) { signer, err := NewFromFiles(testKeyfile, testPubfile) if err != nil { t.Fatal(err) } // ensure that signing always fails signer.Entity.PrivateKey.PrivateKey = failSigner{} metadataBytes := loadChartMetadataForSigning(t, testChartfile) // Read the chart file data archiveData, err := os.ReadFile(testChartfile) if err != nil { t.Fatal(err) } sig, err := signer.ClearSign(archiveData, filepath.Base(testChartfile), metadataBytes) if err == nil { t.Fatal("didn't get an error from ClearSign but expected one") } if sig != "" { t.Fatalf("expected an empty signature after failed ClearSign but got %q", sig) } } func TestVerify(t *testing.T) { signer, err := NewFromFiles(testKeyfile, testPubfile) if err != nil { t.Fatal(err) } // Read the chart file data archiveData, err := os.ReadFile(testChartfile) if err != nil { t.Fatal(err) } // Read the signature file data sigData, err := os.ReadFile(testSigBlock) if err != nil { t.Fatal(err) } if ver, err := signer.Verify(archiveData, sigData, filepath.Base(testChartfile)); err != nil { t.Errorf("Failed to pass verify. Err: %s", err) } else if len(ver.FileHash) == 0 { t.Error("Verification is missing hash.") } else if ver.SignedBy == nil { t.Error("No SignedBy field") } else if ver.FileName != filepath.Base(testChartfile) { t.Errorf("FileName is unexpectedly %q", ver.FileName) } // Read the tampered signature file data tamperedSigData, err := os.ReadFile(testTamperedSigBlock) if err != nil { t.Fatal(err) } if _, err = signer.Verify(archiveData, tamperedSigData, filepath.Base(testChartfile)); err == nil { t.Errorf("Expected %s to fail.", testTamperedSigBlock) } switch err.(type) { case pgperrors.SignatureError: t.Logf("Tampered sig block error: %s (%T)", err, err) default: t.Errorf("Expected invalid signature error, got %q (%T)", err, err) } } // readSumFile reads a file containing a sum generated by the UNIX shasum tool. func readSumFile(sumfile string) (string, error) { data, err := os.ReadFile(sumfile) if err != nil { return "", err } sig := string(data) parts := strings.SplitN(sig, " ", 2) return parts[0], nil }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/provenance/doc.go
pkg/provenance/doc.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Package provenance provides tools for establishing the authenticity of packages. In Helm, provenance is established via several factors. The primary factor is the cryptographic signature of a package. Package authors may sign packages, which in turn provide the necessary metadata to ensure the integrity of the package file, the metadata, and the referenced Docker images. A provenance file is clear-signed. This provides cryptographic verification that a particular block of information (metadata, archive file, images) have not been tampered with or altered. To learn more, read the GnuPG documentation on clear signatures: https://www.gnupg.org/gph/en/manual/x135.html The cryptography used by Helm should be compatible with OpenGPG. For example, you should be able to verify a signature by importing the desired public key and using `gpg --verify`, `keybase pgp verify`, or similar: $ gpg --verify some.sig gpg: Signature made Mon Jul 25 17:23:44 2016 MDT using RSA key ID 1FC18762 gpg: Good signature from "Helm Testing (This key should only be used for testing. DO NOT TRUST.) <helm-testing@helm.sh>" [ultimate] */ package provenance // import "helm.sh/helm/v4/pkg/provenance"
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/rollback.go
pkg/action/rollback.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package action import ( "bytes" "errors" "fmt" "time" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" chartutil "helm.sh/helm/v4/pkg/chart/v2/util" "helm.sh/helm/v4/pkg/kube" "helm.sh/helm/v4/pkg/release/common" release "helm.sh/helm/v4/pkg/release/v1" "helm.sh/helm/v4/pkg/storage/driver" ) // Rollback is the action for rolling back to a given release. // // It provides the implementation of 'helm rollback'. type Rollback struct { cfg *Configuration Version int Timeout time.Duration WaitStrategy kube.WaitStrategy WaitForJobs bool DisableHooks bool // DryRunStrategy can be set to prepare, but not execute the operation and whether or not to interact with the remote cluster DryRunStrategy DryRunStrategy // ForceReplace will, if set to `true`, ignore certain warnings and perform the rollback anyway. // // This should be used with caution. ForceReplace bool // ForceConflicts causes server-side apply to force conflicts ("Overwrite value, become sole manager") // see: https://kubernetes.io/docs/reference/using-api/server-side-apply/#conflicts ForceConflicts bool // ServerSideApply enables changes to be applied via Kubernetes server-side apply // Can be the string: "true", "false" or "auto" // When "auto", sever-side usage will be based upon the releases previous usage // see: https://kubernetes.io/docs/reference/using-api/server-side-apply/ ServerSideApply string CleanupOnFail bool MaxHistory int // MaxHistory limits the maximum number of revisions saved per release } // NewRollback creates a new Rollback object with the given configuration. func NewRollback(cfg *Configuration) *Rollback { return &Rollback{ cfg: cfg, DryRunStrategy: DryRunNone, } } // Run executes 'helm rollback' against the given release. func (r *Rollback) Run(name string) error { if err := r.cfg.KubeClient.IsReachable(); err != nil { return err } r.cfg.Releases.MaxHistory = r.MaxHistory r.cfg.Logger().Debug("preparing rollback", "name", name) currentRelease, targetRelease, serverSideApply, err := r.prepareRollback(name) if err != nil { return err } if !isDryRun(r.DryRunStrategy) { r.cfg.Logger().Debug("creating rolled back release", "name", name) if err := r.cfg.Releases.Create(targetRelease); err != nil { return err } } r.cfg.Logger().Debug("performing rollback", "name", name) if _, err := r.performRollback(currentRelease, targetRelease, serverSideApply); err != nil { return err } if !isDryRun(r.DryRunStrategy) { r.cfg.Logger().Debug("updating status for rolled back release", "name", name) if err := r.cfg.Releases.Update(targetRelease); err != nil { return err } } return nil } // prepareRollback finds the previous release and prepares a new release object with // the previous release's configuration func (r *Rollback) prepareRollback(name string) (*release.Release, *release.Release, bool, error) { if err := chartutil.ValidateReleaseName(name); err != nil { return nil, nil, false, fmt.Errorf("prepareRollback: Release name is invalid: %s", name) } if r.Version < 0 { return nil, nil, false, errInvalidRevision } currentReleasei, err := r.cfg.Releases.Last(name) if err != nil { return nil, nil, false, err } currentRelease, err := releaserToV1Release(currentReleasei) if err != nil { return nil, nil, false, err } previousVersion := r.Version if r.Version == 0 { previousVersion = currentRelease.Version - 1 } historyReleases, err := r.cfg.Releases.History(name) if err != nil { return nil, nil, false, err } // Check if the history version to be rolled back exists previousVersionExist := false for _, historyReleasei := range historyReleases { historyRelease, err := releaserToV1Release(historyReleasei) if err != nil { return nil, nil, false, err } version := historyRelease.Version if previousVersion == version { previousVersionExist = true break } } if !previousVersionExist { return nil, nil, false, fmt.Errorf("release has no %d version", previousVersion) } r.cfg.Logger().Debug("rolling back", "name", name, "currentVersion", currentRelease.Version, "targetVersion", previousVersion) previousReleasei, err := r.cfg.Releases.Get(name, previousVersion) if err != nil { return nil, nil, false, err } previousRelease, err := releaserToV1Release(previousReleasei) if err != nil { return nil, nil, false, err } serverSideApply, err := getUpgradeServerSideValue(r.ServerSideApply, previousRelease.ApplyMethod) if err != nil { return nil, nil, false, err } // Store a new release object with previous release's configuration targetRelease := &release.Release{ Name: name, Namespace: currentRelease.Namespace, Chart: previousRelease.Chart, Config: previousRelease.Config, Info: &release.Info{ FirstDeployed: currentRelease.Info.FirstDeployed, LastDeployed: time.Now(), Status: common.StatusPendingRollback, Notes: previousRelease.Info.Notes, // Because we lose the reference to previous version elsewhere, we set the // message here, and only override it later if we experience failure. Description: fmt.Sprintf("Rollback to %d", previousVersion), }, Version: currentRelease.Version + 1, Labels: previousRelease.Labels, Manifest: previousRelease.Manifest, Hooks: previousRelease.Hooks, ApplyMethod: string(determineReleaseSSApplyMethod(serverSideApply)), } return currentRelease, targetRelease, serverSideApply, nil } func (r *Rollback) performRollback(currentRelease, targetRelease *release.Release, serverSideApply bool) (*release.Release, error) { if isDryRun(r.DryRunStrategy) { r.cfg.Logger().Debug("dry run", "name", targetRelease.Name) return targetRelease, nil } current, err := r.cfg.KubeClient.Build(bytes.NewBufferString(currentRelease.Manifest), false) if err != nil { return targetRelease, fmt.Errorf("unable to build kubernetes objects from current release manifest: %w", err) } target, err := r.cfg.KubeClient.Build(bytes.NewBufferString(targetRelease.Manifest), false) if err != nil { return targetRelease, fmt.Errorf("unable to build kubernetes objects from new release manifest: %w", err) } // pre-rollback hooks if !r.DisableHooks { if err := r.cfg.execHook(targetRelease, release.HookPreRollback, r.WaitStrategy, r.Timeout, serverSideApply); err != nil { return targetRelease, err } } else { r.cfg.Logger().Debug("rollback hooks disabled", "name", targetRelease.Name) } // It is safe to use "forceOwnership" here because these are resources currently rendered by the chart. err = target.Visit(setMetadataVisitor(targetRelease.Name, targetRelease.Namespace, true)) if err != nil { return targetRelease, fmt.Errorf("unable to set metadata visitor from target release: %w", err) } results, err := r.cfg.KubeClient.Update( current, target, kube.ClientUpdateOptionForceReplace(r.ForceReplace), kube.ClientUpdateOptionServerSideApply(serverSideApply, r.ForceConflicts), kube.ClientUpdateOptionThreeWayMergeForUnstructured(false), kube.ClientUpdateOptionUpgradeClientSideFieldManager(true)) if err != nil { msg := fmt.Sprintf("Rollback %q failed: %s", targetRelease.Name, err) r.cfg.Logger().Warn(msg) currentRelease.Info.Status = common.StatusSuperseded targetRelease.Info.Status = common.StatusFailed targetRelease.Info.Description = msg r.cfg.recordRelease(currentRelease) r.cfg.recordRelease(targetRelease) if r.CleanupOnFail { r.cfg.Logger().Debug("cleanup on fail set, cleaning up resources", "count", len(results.Created)) _, errs := r.cfg.KubeClient.Delete(results.Created, metav1.DeletePropagationBackground) if errs != nil { return targetRelease, fmt.Errorf( "an error occurred while cleaning up resources. original rollback error: %w", fmt.Errorf("unable to cleanup resources: %w", joinErrors(errs, ", "))) } r.cfg.Logger().Debug("resource cleanup complete") } return targetRelease, err } waiter, err := r.cfg.KubeClient.GetWaiter(r.WaitStrategy) if err != nil { return nil, fmt.Errorf("unable to get waiter: %w", err) } if r.WaitForJobs { if err := waiter.WaitWithJobs(target, r.Timeout); err != nil { targetRelease.SetStatus(common.StatusFailed, fmt.Sprintf("Release %q failed: %s", targetRelease.Name, err.Error())) r.cfg.recordRelease(currentRelease) r.cfg.recordRelease(targetRelease) return targetRelease, fmt.Errorf("release %s failed: %w", targetRelease.Name, err) } } else { if err := waiter.Wait(target, r.Timeout); err != nil { targetRelease.SetStatus(common.StatusFailed, fmt.Sprintf("Release %q failed: %s", targetRelease.Name, err.Error())) r.cfg.recordRelease(currentRelease) r.cfg.recordRelease(targetRelease) return targetRelease, fmt.Errorf("release %s failed: %w", targetRelease.Name, err) } } // post-rollback hooks if !r.DisableHooks { if err := r.cfg.execHook(targetRelease, release.HookPostRollback, r.WaitStrategy, r.Timeout, serverSideApply); err != nil { return targetRelease, err } } deployed, err := r.cfg.Releases.DeployedAll(currentRelease.Name) if err != nil && !errors.Is(err, driver.ErrNoDeployedReleases) { return nil, err } // Supersede all previous deployments, see issue #2941. for _, reli := range deployed { rel, err := releaserToV1Release(reli) if err != nil { return nil, err } r.cfg.Logger().Debug("superseding previous deployment", "version", rel.Version) rel.Info.Status = common.StatusSuperseded r.cfg.recordRelease(rel) } targetRelease.Info.Status = common.StatusDeployed return targetRelease, nil }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/history_test.go
pkg/action/history_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package action import ( "errors" "io" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" kubefake "helm.sh/helm/v4/pkg/kube/fake" release "helm.sh/helm/v4/pkg/release/v1" "helm.sh/helm/v4/pkg/release/common" ) func TestNewHistory(t *testing.T) { config := actionConfigFixture(t) client := NewHistory(config) assert.NotNil(t, client) assert.Equal(t, config, client.cfg) } func TestHistoryRun(t *testing.T) { releaseName := "test-release" simpleRelease := namedReleaseStub(releaseName, common.StatusPendingUpgrade) updatedRelease := namedReleaseStub(releaseName, common.StatusDeployed) updatedRelease.Chart.Metadata.Version = "0.1.1" updatedRelease.Version = 2 config := actionConfigFixture(t) client := NewHistory(config) client.Max = 3 client.cfg.Releases.MaxHistory = 3 for _, rel := range []*release.Release{simpleRelease, updatedRelease} { if err := client.cfg.Releases.Create(rel); err != nil { t.Fatal(err, "Could not add releases to Config") } } releases, err := config.Releases.ListReleases() require.NoError(t, err) assert.Len(t, releases, 2, "expected 2 Releases in Config") releasers, err := client.Run(releaseName) require.NoError(t, err) assert.Len(t, releasers, 2, "expected 2 Releases in History result") release1, err := releaserToV1Release(releasers[0]) require.NoError(t, err) assert.Equal(t, simpleRelease.Name, release1.Name) assert.Equal(t, simpleRelease.Version, release1.Version) release2, err := releaserToV1Release(releasers[1]) require.NoError(t, err) assert.Equal(t, updatedRelease.Name, release2.Name) assert.Equal(t, updatedRelease.Version, release2.Version) } func TestHistoryRun_UnreachableKubeClient(t *testing.T) { config := actionConfigFixture(t) failingKubeClient := kubefake.FailingKubeClient{PrintingKubeClient: kubefake.PrintingKubeClient{Out: io.Discard}, DummyResources: nil} failingKubeClient.ConnectionError = errors.New("connection refused") config.KubeClient = &failingKubeClient client := NewHistory(config) result, err := client.Run("release-name") assert.Nil(t, result) assert.Error(t, err) } func TestHistoryRun_InvalidReleaseNames(t *testing.T) { config := actionConfigFixture(t) client := NewHistory(config) invalidReleaseNames := []string{ "", "too-long-release-name-max-53-characters-abcdefghijklmnopqrstuvwxyz", "MyRelease", "release_name", "release@123", "-badstart", "badend-", ".dotstart", } for _, name := range invalidReleaseNames { result, err := client.Run(name) assert.Nil(t, result) assert.ErrorContains(t, err, "release name is invalid") } }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/push_test.go
pkg/action/push_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package action import ( "bytes" "testing" "github.com/stretchr/testify/assert" ) func TestNewPushWithPushConfig(t *testing.T) { config := actionConfigFixture(t) client := NewPushWithOpts(WithPushConfig(config)) assert.NotNil(t, client) assert.Equal(t, config, client.cfg) } func TestNewPushWithTLSClientConfig(t *testing.T) { certFile := "certFile" keyFile := "keyFile" caFile := "caFile" client := NewPushWithOpts(WithTLSClientConfig(certFile, keyFile, caFile)) assert.NotNil(t, client) assert.Equal(t, certFile, client.certFile) assert.Equal(t, keyFile, client.keyFile) assert.Equal(t, caFile, client.caFile) } func TestNewPushWithInsecureSkipTLSVerify(t *testing.T) { client := NewPushWithOpts(WithInsecureSkipTLSVerify(true)) assert.NotNil(t, client) assert.Equal(t, true, client.insecureSkipTLSVerify) } func TestNewPushWithPlainHTTP(t *testing.T) { client := NewPushWithOpts(WithPlainHTTP(true)) assert.NotNil(t, client) assert.Equal(t, true, client.plainHTTP) } func TestNewPushWithPushOptWriter(t *testing.T) { buf := new(bytes.Buffer) client := NewPushWithOpts(WithPushOptWriter(buf)) assert.NotNil(t, client) assert.Equal(t, buf, client.out) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/show.go
pkg/action/show.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package action import ( "bytes" "fmt" "strings" "k8s.io/cli-runtime/pkg/printers" "sigs.k8s.io/yaml" "helm.sh/helm/v4/pkg/chart/common" chart "helm.sh/helm/v4/pkg/chart/v2" "helm.sh/helm/v4/pkg/chart/v2/loader" chartutil "helm.sh/helm/v4/pkg/chart/v2/util" "helm.sh/helm/v4/pkg/registry" ) // ShowOutputFormat is the format of the output of `helm show` type ShowOutputFormat string const ( // ShowAll is the format which shows all the information of a chart ShowAll ShowOutputFormat = "all" // ShowChart is the format which only shows the chart's definition ShowChart ShowOutputFormat = "chart" // ShowValues is the format which only shows the chart's values ShowValues ShowOutputFormat = "values" // ShowReadme is the format which only shows the chart's README ShowReadme ShowOutputFormat = "readme" // ShowCRDs is the format which only shows the chart's CRDs ShowCRDs ShowOutputFormat = "crds" ) var readmeFileNames = []string{"readme.md", "readme.txt", "readme"} func (o ShowOutputFormat) String() string { return string(o) } // Show is the action for checking a given release's information. // // It provides the implementation of 'helm show' and its respective subcommands. type Show struct { ChartPathOptions Devel bool OutputFormat ShowOutputFormat JSONPathTemplate string chart *chart.Chart // for testing } // NewShow creates a new Show object with the given configuration. func NewShow(output ShowOutputFormat, cfg *Configuration) *Show { sh := &Show{ OutputFormat: output, } sh.registryClient = cfg.RegistryClient return sh } // SetRegistryClient sets the registry client to use when pulling a chart from a registry. func (s *Show) SetRegistryClient(client *registry.Client) { s.registryClient = client } // Run executes 'helm show' against the given release. func (s *Show) Run(chartpath string) (string, error) { if s.chart == nil { chrt, err := loader.Load(chartpath) if err != nil { return "", err } s.chart = chrt } cf, err := yaml.Marshal(s.chart.Metadata) if err != nil { return "", err } var out strings.Builder if s.OutputFormat == ShowChart || s.OutputFormat == ShowAll { fmt.Fprintf(&out, "%s\n", cf) } if (s.OutputFormat == ShowValues || s.OutputFormat == ShowAll) && s.chart.Values != nil { if s.OutputFormat == ShowAll { fmt.Fprintln(&out, "---") } if s.JSONPathTemplate != "" { printer, err := printers.NewJSONPathPrinter(s.JSONPathTemplate) if err != nil { return "", fmt.Errorf("error parsing jsonpath %s: %w", s.JSONPathTemplate, err) } printer.Execute(&out, s.chart.Values) } else { for _, f := range s.chart.Raw { if f.Name == chartutil.ValuesfileName { fmt.Fprintln(&out, string(f.Data)) } } } } if s.OutputFormat == ShowReadme || s.OutputFormat == ShowAll { readme := findReadme(s.chart.Files) if readme != nil { if s.OutputFormat == ShowAll { fmt.Fprintln(&out, "---") } fmt.Fprintf(&out, "%s\n", readme.Data) } } if s.OutputFormat == ShowCRDs || s.OutputFormat == ShowAll { crds := s.chart.CRDObjects() if len(crds) > 0 { for _, crd := range crds { if !bytes.HasPrefix(crd.File.Data, []byte("---")) { fmt.Fprintln(&out, "---") } fmt.Fprintf(&out, "%s\n", string(crd.File.Data)) } } } return out.String(), nil } func findReadme(files []*common.File) (file *common.File) { for _, file := range files { for _, n := range readmeFileNames { if file == nil { continue } if strings.EqualFold(file.Name, n) { return file } } } return nil }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/get_metadata.go
pkg/action/get_metadata.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package action import ( "errors" "log/slog" "sort" "strings" "time" ci "helm.sh/helm/v4/pkg/chart" chart "helm.sh/helm/v4/pkg/chart/v2" "helm.sh/helm/v4/pkg/release" ) // GetMetadata is the action for checking a given release's metadata. // // It provides the implementation of 'helm get metadata'. type GetMetadata struct { cfg *Configuration Version int } type Metadata struct { Name string `json:"name" yaml:"name"` Chart string `json:"chart" yaml:"chart"` Version string `json:"version" yaml:"version"` AppVersion string `json:"appVersion" yaml:"appVersion"` // Annotations are fetched from the Chart.yaml file Annotations map[string]string `json:"annotations,omitempty" yaml:"annotations,omitempty"` // Labels of the release which are stored in driver metadata fields storage Labels map[string]string `json:"labels,omitempty" yaml:"labels,omitempty"` Dependencies []ci.Dependency `json:"dependencies,omitempty" yaml:"dependencies,omitempty"` Namespace string `json:"namespace" yaml:"namespace"` Revision int `json:"revision" yaml:"revision"` Status string `json:"status" yaml:"status"` DeployedAt string `json:"deployedAt" yaml:"deployedAt"` ApplyMethod string `json:"applyMethod,omitempty" yaml:"applyMethod,omitempty"` } // NewGetMetadata creates a new GetMetadata object with the given configuration. func NewGetMetadata(cfg *Configuration) *GetMetadata { return &GetMetadata{ cfg: cfg, } } // Run executes 'helm get metadata' against the given release. func (g *GetMetadata) Run(name string) (*Metadata, error) { if err := g.cfg.KubeClient.IsReachable(); err != nil { return nil, err } rel, err := g.cfg.releaseContent(name, g.Version) if err != nil { return nil, err } rac, err := release.NewAccessor(rel) if err != nil { return nil, err } ac, err := ci.NewAccessor(rac.Chart()) if err != nil { return nil, err } charti := rac.Chart() var chrt *chart.Chart switch c := charti.(type) { case *chart.Chart: chrt = c case chart.Chart: chrt = &c default: return nil, errors.New("invalid chart apiVersion") } return &Metadata{ Name: rac.Name(), Chart: chrt.Metadata.Name, Version: chrt.Metadata.Version, AppVersion: chrt.Metadata.AppVersion, Dependencies: ac.MetaDependencies(), Annotations: chrt.Metadata.Annotations, Labels: rac.Labels(), Namespace: rac.Namespace(), Revision: rac.Version(), Status: rac.Status(), DeployedAt: rac.DeployedAt().Format(time.RFC3339), ApplyMethod: rac.ApplyMethod(), }, nil } // FormattedDepNames formats metadata.dependencies names into a comma-separated list. func (m *Metadata) FormattedDepNames() string { depsNames := make([]string, 0, len(m.Dependencies)) for _, dep := range m.Dependencies { ac, err := ci.NewDependencyAccessor(dep) if err != nil { slog.Error("unable to access dependency metadata", "error", err) continue } depsNames = append(depsNames, ac.Name()) } sort.StringSlice(depsNames).Sort() return strings.Join(depsNames, ",") }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/verify.go
pkg/action/verify.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package action import ( "fmt" "strings" "helm.sh/helm/v4/pkg/downloader" ) // Verify is the action for building a given chart's Verify tree. // // It provides the implementation of 'helm verify'. type Verify struct { Keyring string } // NewVerify creates a new Verify object with the given configuration. func NewVerify() *Verify { return &Verify{} } // Run executes 'helm verify'. func (v *Verify) Run(chartfile string) (string, error) { var out strings.Builder p, err := downloader.VerifyChart(chartfile, chartfile+".prov", v.Keyring) if err != nil { return "", err } for name := range p.SignedBy.Identities { _, _ = fmt.Fprintf(&out, "Signed by: %v\n", name) } _, _ = fmt.Fprintf(&out, "Using Key With Fingerprint: %X\n", p.SignedBy.PrimaryKey.Fingerprint) _, _ = fmt.Fprintf(&out, "Chart Hash Verified: %s\n", p.FileHash) return out.String(), err }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/lint_test.go
pkg/action/lint_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package action import ( "errors" "testing" "github.com/stretchr/testify/assert" "helm.sh/helm/v4/pkg/chart/v2/lint/support" ) var ( values = make(map[string]interface{}) namespace = "testNamespace" chart1MultipleChartLint = "testdata/charts/multiplecharts-lint-chart-1" chart2MultipleChartLint = "testdata/charts/multiplecharts-lint-chart-2" corruptedTgzChart = "testdata/charts/corrupted-compressed-chart.tgz" chartWithNoTemplatesDir = "testdata/charts/chart-with-no-templates-dir" ) func TestLintChart(t *testing.T) { tests := []struct { name string chartPath string err bool skipSchemaValidation bool }{ { name: "decompressed-chart", chartPath: "testdata/charts/decompressedchart/", }, { name: "archived-chart-path", chartPath: "testdata/charts/compressedchart-0.1.0.tgz", }, { name: "archived-chart-path-with-hyphens", chartPath: "testdata/charts/compressedchart-with-hyphens-0.1.0.tgz", }, { name: "archived-tar-gz-chart-path", chartPath: "testdata/charts/compressedchart-0.1.0.tar.gz", }, { name: "invalid-archived-chart-path", chartPath: "testdata/charts/invalidcompressedchart0.1.0.tgz", err: true, }, { name: "chart-missing-manifest", chartPath: "testdata/charts/chart-missing-manifest", err: true, }, { name: "chart-with-schema", chartPath: "testdata/charts/chart-with-schema", }, { name: "chart-with-schema-negative", chartPath: "testdata/charts/chart-with-schema-negative", }, { name: "chart-with-schema-negative-skip-validation", chartPath: "testdata/charts/chart-with-schema-negative", skipSchemaValidation: true, }, { name: "pre-release-chart", chartPath: "testdata/charts/pre-release-chart-0.1.0-alpha.tgz", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { _, err := lintChart(tt.chartPath, map[string]interface{}{}, namespace, nil, tt.skipSchemaValidation) switch { case err != nil && !tt.err: t.Errorf("%s", err) case err == nil && tt.err: t.Errorf("Expected a chart parsing error") } }) } } func TestNonExistentChart(t *testing.T) { t.Run("should error out for non existent tgz chart", func(t *testing.T) { testCharts := []string{"non-existent-chart.tgz"} expectedError := "unable to open tarball: open non-existent-chart.tgz: no such file or directory" testLint := NewLint() result := testLint.Run(testCharts, values) if len(result.Errors) != 1 { t.Error("expected one error, but got", len(result.Errors)) } actual := result.Errors[0].Error() if actual != expectedError { t.Errorf("expected '%s', but got '%s'", expectedError, actual) } }) t.Run("should error out for corrupted tgz chart", func(t *testing.T) { testCharts := []string{corruptedTgzChart} expectedEOFError := "unable to extract tarball: EOF" testLint := NewLint() result := testLint.Run(testCharts, values) if len(result.Errors) != 1 { t.Error("expected one error, but got", len(result.Errors)) } actual := result.Errors[0].Error() if actual != expectedEOFError { t.Errorf("expected '%s', but got '%s'", expectedEOFError, actual) } }) } func TestLint_MultipleCharts(t *testing.T) { testCharts := []string{chart2MultipleChartLint, chart1MultipleChartLint} testLint := NewLint() if result := testLint.Run(testCharts, values); len(result.Errors) > 0 { t.Error(result.Errors) } } func TestLint_EmptyResultErrors(t *testing.T) { testCharts := []string{chart2MultipleChartLint} testLint := NewLint() if result := testLint.Run(testCharts, values); len(result.Errors) > 0 { t.Error("Expected no error, got more") } } func TestLint_ChartWithWarnings(t *testing.T) { t.Run("should pass when not strict", func(t *testing.T) { testCharts := []string{chartWithNoTemplatesDir} testLint := NewLint() testLint.Strict = false if result := testLint.Run(testCharts, values); len(result.Errors) > 0 { t.Error("Expected no error, got more") } }) t.Run("should fail with one error when strict", func(t *testing.T) { testCharts := []string{chartWithNoTemplatesDir} testLint := NewLint() testLint.Strict = true if result := testLint.Run(testCharts, values); len(result.Errors) != 1 { t.Error("expected one error, but got", len(result.Errors)) } }) } func TestHasWarningsOrErrors(t *testing.T) { testError := errors.New("test-error") cases := []struct { name string data LintResult expected bool }{ { name: "has no warning messages and no errors", data: LintResult{TotalChartsLinted: 1, Messages: make([]support.Message, 0), Errors: make([]error, 0)}, expected: false, }, { name: "has error", data: LintResult{TotalChartsLinted: 1, Messages: make([]support.Message, 0), Errors: []error{testError}}, expected: true, }, { name: "has info message only", data: LintResult{TotalChartsLinted: 1, Messages: []support.Message{{Severity: support.InfoSev, Path: "", Err: testError}}, Errors: make([]error, 0)}, expected: false, }, { name: "has warning message", data: LintResult{TotalChartsLinted: 1, Messages: []support.Message{{Severity: support.WarningSev, Path: "", Err: testError}}, Errors: make([]error, 0)}, expected: true, }, { name: "has error message", data: LintResult{TotalChartsLinted: 1, Messages: []support.Message{{Severity: support.ErrorSev, Path: "", Err: testError}}, Errors: make([]error, 0)}, expected: true, }, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { result := HasWarningsOrErrors(&tc.data) assert.Equal(t, tc.expected, result) }) } }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/action_test.go
pkg/action/action_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package action import ( "bytes" "errors" "flag" "fmt" "io" "log/slog" "strings" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" fakeclientset "k8s.io/client-go/kubernetes/fake" "helm.sh/helm/v4/internal/logging" "helm.sh/helm/v4/pkg/chart/common" chart "helm.sh/helm/v4/pkg/chart/v2" "helm.sh/helm/v4/pkg/kube" kubefake "helm.sh/helm/v4/pkg/kube/fake" "helm.sh/helm/v4/pkg/registry" rcommon "helm.sh/helm/v4/pkg/release/common" release "helm.sh/helm/v4/pkg/release/v1" "helm.sh/helm/v4/pkg/storage" "helm.sh/helm/v4/pkg/storage/driver" ) var verbose = flag.Bool("test.log", false, "enable test logging (debug by default)") func actionConfigFixture(t *testing.T) *Configuration { t.Helper() return actionConfigFixtureWithDummyResources(t, nil) } func actionConfigFixtureWithDummyResources(t *testing.T, dummyResources kube.ResourceList) *Configuration { t.Helper() logger := logging.NewLogger(func() bool { return *verbose }) slog.SetDefault(logger) registryClient, err := registry.NewClient() if err != nil { t.Fatal(err) } return &Configuration{ Releases: storage.Init(driver.NewMemory()), KubeClient: &kubefake.FailingKubeClient{PrintingKubeClient: kubefake.PrintingKubeClient{Out: io.Discard}, DummyResources: dummyResources}, Capabilities: common.DefaultCapabilities, RegistryClient: registryClient, } } var manifestWithHook = `kind: ConfigMap metadata: name: test-cm annotations: "helm.sh/hook": post-install,pre-delete,post-upgrade data: name: value` var manifestWithTestHook = `kind: Pod metadata: name: finding-nemo, annotations: "helm.sh/hook": test spec: containers: - name: nemo-test image: fake-image cmd: fake-command ` var rbacManifests = `apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: name: schedule-agents rules: - apiGroups: [""] resources: ["pods", "pods/exec", "pods/log"] verbs: ["*"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: schedule-agents namespace: {{ default .Release.Namespace}} roleRef: apiGroup: rbac.authorization.k8s.io kind: Role name: schedule-agents subjects: - kind: ServiceAccount name: schedule-agents namespace: {{ .Release.Namespace }} ` type chartOptions struct { *chart.Chart } type chartOption func(*chartOptions) func buildChart(opts ...chartOption) *chart.Chart { modTime := time.Now() defaultTemplates := []*common.File{ {Name: "templates/hello", ModTime: modTime, Data: []byte("hello: world")}, {Name: "templates/hooks", ModTime: modTime, Data: []byte(manifestWithHook)}, } return buildChartWithTemplates(defaultTemplates, opts...) } func buildChartWithTemplates(templates []*common.File, opts ...chartOption) *chart.Chart { c := &chartOptions{ Chart: &chart.Chart{ // TODO: This should be more complete. Metadata: &chart.Metadata{ APIVersion: "v1", Name: "hello", Version: "0.1.0", }, Templates: templates, }, } for _, opt := range opts { opt(c) } return c.Chart } func withName(name string) chartOption { return func(opts *chartOptions) { opts.Metadata.Name = name } } func withSampleValues() chartOption { values := map[string]interface{}{ "someKey": "someValue", "nestedKey": map[string]interface{}{ "simpleKey": "simpleValue", "anotherNestedKey": map[string]interface{}{ "yetAnotherNestedKey": map[string]interface{}{ "youReadyForAnotherNestedKey": "No", }, }, }, } return func(opts *chartOptions) { opts.Values = values } } func withValues(values map[string]interface{}) chartOption { return func(opts *chartOptions) { opts.Values = values } } func withNotes(notes string) chartOption { return func(opts *chartOptions) { opts.Templates = append(opts.Templates, &common.File{ Name: "templates/NOTES.txt", ModTime: time.Now(), Data: []byte(notes), }) } } func withDependency(dependencyOpts ...chartOption) chartOption { return func(opts *chartOptions) { opts.AddDependency(buildChart(dependencyOpts...)) } } func withMetadataDependency(dependency chart.Dependency) chartOption { return func(opts *chartOptions) { opts.Metadata.Dependencies = append(opts.Metadata.Dependencies, &dependency) } } func withFile(file common.File) chartOption { return func(opts *chartOptions) { opts.Files = append(opts.Files, &file) } } func withSampleTemplates() chartOption { return func(opts *chartOptions) { modTime := time.Now() sampleTemplates := []*common.File{ // This adds basic templates and partials. {Name: "templates/goodbye", ModTime: modTime, Data: []byte("goodbye: world")}, {Name: "templates/empty", ModTime: modTime, Data: []byte("")}, {Name: "templates/with-partials", ModTime: modTime, Data: []byte(`hello: {{ template "_planet" . }}`)}, {Name: "templates/partials/_planet", ModTime: modTime, Data: []byte(`{{define "_planet"}}Earth{{end}}`)}, } opts.Templates = append(opts.Templates, sampleTemplates...) } } func withSampleSecret() chartOption { return func(opts *chartOptions) { sampleSecret := &common.File{Name: "templates/secret.yaml", ModTime: time.Now(), Data: []byte("apiVersion: v1\nkind: Secret\n")} opts.Templates = append(opts.Templates, sampleSecret) } } func withSampleIncludingIncorrectTemplates() chartOption { return func(opts *chartOptions) { modTime := time.Now() sampleTemplates := []*common.File{ // This adds basic templates and partials. {Name: "templates/goodbye", ModTime: modTime, Data: []byte("goodbye: world")}, {Name: "templates/empty", ModTime: modTime, Data: []byte("")}, {Name: "templates/incorrect", ModTime: modTime, Data: []byte("{{ .Values.bad.doh }}")}, {Name: "templates/with-partials", ModTime: modTime, Data: []byte(`hello: {{ template "_planet" . }}`)}, {Name: "templates/partials/_planet", ModTime: modTime, Data: []byte(`{{define "_planet"}}Earth{{end}}`)}, } opts.Templates = append(opts.Templates, sampleTemplates...) } } func withMultipleManifestTemplate() chartOption { return func(opts *chartOptions) { sampleTemplates := []*common.File{ {Name: "templates/rbac", ModTime: time.Now(), Data: []byte(rbacManifests)}, } opts.Templates = append(opts.Templates, sampleTemplates...) } } func withKube(version string) chartOption { return func(opts *chartOptions) { opts.Metadata.KubeVersion = version } } // releaseStub creates a release stub, complete with the chartStub as its chart. func releaseStub() *release.Release { return namedReleaseStub("angry-panda", rcommon.StatusDeployed) } func namedReleaseStub(name string, status rcommon.Status) *release.Release { now := time.Now() return &release.Release{ Name: name, Info: &release.Info{ FirstDeployed: now, LastDeployed: now, Status: status, Description: "Named Release Stub", }, Chart: buildChart(withSampleTemplates()), Config: map[string]interface{}{"name": "value"}, Version: 1, Hooks: []*release.Hook{ { Name: "test-cm", Kind: "ConfigMap", Path: "test-cm", Manifest: manifestWithHook, Events: []release.HookEvent{ release.HookPostInstall, release.HookPreDelete, }, }, { Name: "finding-nemo", Kind: "Pod", Path: "finding-nemo", Manifest: manifestWithTestHook, Events: []release.HookEvent{ release.HookTest, }, }, }, } } func TestConfiguration_Init(t *testing.T) { tests := []struct { name string helmDriver string expectedDriverType interface{} expectErr bool errMsg string }{ { name: "Test secret driver", helmDriver: "secret", expectedDriverType: &driver.Secrets{}, }, { name: "Test secrets driver", helmDriver: "secrets", expectedDriverType: &driver.Secrets{}, }, { name: "Test empty driver", helmDriver: "", expectedDriverType: &driver.Secrets{}, }, { name: "Test configmap driver", helmDriver: "configmap", expectedDriverType: &driver.ConfigMaps{}, }, { name: "Test configmaps driver", helmDriver: "configmaps", expectedDriverType: &driver.ConfigMaps{}, }, { name: "Test memory driver", helmDriver: "memory", expectedDriverType: &driver.Memory{}, }, { name: "Test sql driver", helmDriver: "sql", expectErr: true, errMsg: "unable to instantiate SQL driver", }, { name: "Test unknown driver", helmDriver: "someDriver", expectErr: true, errMsg: fmt.Sprintf("unknown driver %q", "someDriver"), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { cfg := NewConfiguration() actualErr := cfg.Init(nil, "default", tt.helmDriver) if tt.expectErr { assert.Error(t, actualErr) assert.Contains(t, actualErr.Error(), tt.errMsg) } else { assert.NoError(t, actualErr) assert.IsType(t, tt.expectedDriverType, cfg.Releases.Driver) } }) } } func TestGetVersionSet(t *testing.T) { client := fakeclientset.NewClientset() vs, err := GetVersionSet(client.Discovery()) if err != nil { t.Error(err) } if !vs.Has("v1") { t.Errorf("Expected supported versions to at least include v1.") } if vs.Has("nosuchversion/v1") { t.Error("Non-existent version is reported found.") } } // Mock PostRenderer for testing type mockPostRenderer struct { shouldError bool transform func(string) string } func (m *mockPostRenderer) Run(renderedManifests *bytes.Buffer) (*bytes.Buffer, error) { if m.shouldError { return nil, errors.New("mock post-renderer error") } content := renderedManifests.String() if m.transform != nil { content = m.transform(content) } return bytes.NewBufferString(content), nil } func TestAnnotateAndMerge(t *testing.T) { tests := []struct { name string files map[string]string expectedError string expected string }{ { name: "no files", files: map[string]string{}, expected: "", }, { name: "single file with single manifest", files: map[string]string{ "templates/configmap.yaml": `apiVersion: v1 kind: ConfigMap metadata: name: test-cm data: key: value`, }, expected: `apiVersion: v1 kind: ConfigMap metadata: name: test-cm annotations: postrenderer.helm.sh/postrender-filename: 'templates/configmap.yaml' data: key: value `, }, { name: "multiple files with multiple manifests", files: map[string]string{ "templates/configmap.yaml": `apiVersion: v1 kind: ConfigMap metadata: name: test-cm data: key: value`, "templates/secret.yaml": `apiVersion: v1 kind: Secret metadata: name: test-secret data: password: dGVzdA==`, }, expected: `apiVersion: v1 kind: ConfigMap metadata: name: test-cm annotations: postrenderer.helm.sh/postrender-filename: 'templates/configmap.yaml' data: key: value --- apiVersion: v1 kind: Secret metadata: name: test-secret annotations: postrenderer.helm.sh/postrender-filename: 'templates/secret.yaml' data: password: dGVzdA== `, }, { name: "file with multiple manifests", files: map[string]string{ "templates/multi.yaml": `apiVersion: v1 kind: ConfigMap metadata: name: test-cm1 data: key: value1 --- apiVersion: v1 kind: ConfigMap metadata: name: test-cm2 data: key: value2`, }, expected: `apiVersion: v1 kind: ConfigMap metadata: name: test-cm1 annotations: postrenderer.helm.sh/postrender-filename: 'templates/multi.yaml' data: key: value1 --- apiVersion: v1 kind: ConfigMap metadata: name: test-cm2 annotations: postrenderer.helm.sh/postrender-filename: 'templates/multi.yaml' data: key: value2 `, }, { name: "partials and empty files are removed", files: map[string]string{ "templates/cm.yaml": `apiVersion: v1 kind: ConfigMap metadata: name: test-cm1 `, "templates/_partial.tpl": ` {{-define name}} {{- "abracadabra"}} {{- end -}}`, "templates/empty.yaml": ``, }, expected: `apiVersion: v1 kind: ConfigMap metadata: name: test-cm1 annotations: postrenderer.helm.sh/postrender-filename: 'templates/cm.yaml' `, }, { name: "empty file", files: map[string]string{ "templates/empty.yaml": "", }, expected: ``, }, { name: "invalid yaml", files: map[string]string{ "templates/invalid.yaml": `invalid: yaml: content: - malformed`, }, expectedError: "parsing templates/invalid.yaml", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { merged, err := annotateAndMerge(tt.files) if tt.expectedError != "" { assert.Error(t, err) assert.Contains(t, err.Error(), tt.expectedError) } else { assert.NoError(t, err) assert.NotNil(t, merged) assert.Equal(t, tt.expected, merged) } }) } } func TestSplitAndDeannotate(t *testing.T) { tests := []struct { name string input string expectedFiles map[string]string expectedError string }{ { name: "single annotated manifest", input: `apiVersion: v1 kind: ConfigMap metadata: name: test-cm annotations: postrenderer.helm.sh/postrender-filename: templates/configmap.yaml data: key: value`, expectedFiles: map[string]string{ "templates/configmap.yaml": `apiVersion: v1 kind: ConfigMap metadata: name: test-cm data: key: value `, }, }, { name: "multiple manifests with different filenames", input: `apiVersion: v1 kind: ConfigMap metadata: name: test-cm annotations: postrenderer.helm.sh/postrender-filename: templates/configmap.yaml data: key: value --- apiVersion: v1 kind: Secret metadata: name: test-secret annotations: postrenderer.helm.sh/postrender-filename: templates/secret.yaml data: password: dGVzdA==`, expectedFiles: map[string]string{ "templates/configmap.yaml": `apiVersion: v1 kind: ConfigMap metadata: name: test-cm data: key: value `, "templates/secret.yaml": `apiVersion: v1 kind: Secret metadata: name: test-secret data: password: dGVzdA== `, }, }, { name: "multiple manifests with same filename", input: `apiVersion: v1 kind: ConfigMap metadata: name: test-cm1 annotations: postrenderer.helm.sh/postrender-filename: templates/multi.yaml data: key: value1 --- apiVersion: v1 kind: ConfigMap metadata: name: test-cm2 annotations: postrenderer.helm.sh/postrender-filename: templates/multi.yaml data: key: value2`, expectedFiles: map[string]string{ "templates/multi.yaml": `apiVersion: v1 kind: ConfigMap metadata: name: test-cm1 data: key: value1 --- apiVersion: v1 kind: ConfigMap metadata: name: test-cm2 data: key: value2 `, }, }, { name: "manifest with other annotations", input: `apiVersion: v1 kind: ConfigMap metadata: name: test-cm annotations: postrenderer.helm.sh/postrender-filename: templates/configmap.yaml other-annotation: should-remain data: key: value`, expectedFiles: map[string]string{ "templates/configmap.yaml": `apiVersion: v1 kind: ConfigMap metadata: name: test-cm annotations: other-annotation: should-remain data: key: value `, }, }, { name: "invalid yaml input", input: "invalid: yaml: content:", expectedError: "error parsing YAML: MalformedYAMLError", }, { name: "manifest without filename annotation", input: `apiVersion: v1 kind: ConfigMap metadata: name: test-cm data: key: value`, expectedFiles: map[string]string{ "generated-by-postrender-0.yaml": `apiVersion: v1 kind: ConfigMap metadata: name: test-cm data: key: value `, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { files, err := splitAndDeannotate(tt.input) if tt.expectedError != "" { assert.Error(t, err) assert.Contains(t, err.Error(), tt.expectedError) } else { assert.NoError(t, err) assert.Equal(t, len(tt.expectedFiles), len(files)) for expectedFile, expectedContent := range tt.expectedFiles { actualContent, exists := files[expectedFile] assert.True(t, exists, "Expected file %s not found", expectedFile) assert.Equal(t, expectedContent, actualContent) } } }) } } func TestAnnotateAndMerge_SplitAndDeannotate_Roundtrip(t *testing.T) { // Test that merge/split operations are symmetric originalFiles := map[string]string{ "templates/configmap.yaml": `apiVersion: v1 kind: ConfigMap metadata: name: test-cm data: key: value`, "templates/secret.yaml": `apiVersion: v1 kind: Secret metadata: name: test-secret data: password: dGVzdA==`, "templates/multi.yaml": `apiVersion: v1 kind: ConfigMap metadata: name: test-cm1 data: key: value1 --- apiVersion: v1 kind: ConfigMap metadata: name: test-cm2 data: key: value2`, } // Merge and annotate merged, err := annotateAndMerge(originalFiles) require.NoError(t, err) // Split and deannotate reconstructed, err := splitAndDeannotate(merged) require.NoError(t, err) // Compare the results assert.Equal(t, len(originalFiles), len(reconstructed)) for filename, originalContent := range originalFiles { reconstructedContent, exists := reconstructed[filename] assert.True(t, exists, "File %s should exist in reconstructed files", filename) // Normalize whitespace for comparison since YAML processing might affect formatting normalizeContent := func(content string) string { return strings.TrimSpace(strings.ReplaceAll(content, "\r\n", "\n")) } assert.Equal(t, normalizeContent(originalContent), normalizeContent(reconstructedContent)) } } func TestRenderResources_PostRenderer_Success(t *testing.T) { cfg := actionConfigFixture(t) // Create a simple mock post-renderer mockPR := &mockPostRenderer{ transform: func(content string) string { content = strings.ReplaceAll(content, "hello", "yellow") content = strings.ReplaceAll(content, "goodbye", "foodpie") return strings.ReplaceAll(content, "test-cm", "test-cm-postrendered") }, } ch := buildChart(withSampleTemplates()) values := map[string]interface{}{} hooks, buf, notes, err := cfg.renderResources( ch, values, "test-release", "", false, false, false, mockPR, false, false, false, ) assert.NoError(t, err) assert.NotNil(t, hooks) assert.NotNil(t, buf) assert.Equal(t, "", notes) expectedBuf := `--- # Source: yellow/templates/foodpie foodpie: world --- # Source: yellow/templates/with-partials yellow: Earth --- # Source: yellow/templates/yellow yellow: world ` expectedHook := `kind: ConfigMap metadata: name: test-cm-postrendered annotations: "helm.sh/hook": post-install,pre-delete,post-upgrade data: name: value` assert.Equal(t, expectedBuf, buf.String()) assert.Len(t, hooks, 1) assert.Equal(t, expectedHook, hooks[0].Manifest) } func TestRenderResources_PostRenderer_Error(t *testing.T) { cfg := actionConfigFixture(t) // Create a post-renderer that returns an error mockPR := &mockPostRenderer{ shouldError: true, } ch := buildChart(withSampleTemplates()) values := map[string]interface{}{} _, _, _, err := cfg.renderResources( ch, values, "test-release", "", false, false, false, mockPR, false, false, false, ) assert.Error(t, err) assert.Contains(t, err.Error(), "error while running post render on files") } func TestRenderResources_PostRenderer_MergeError(t *testing.T) { cfg := actionConfigFixture(t) // Create a mock post-renderer mockPR := &mockPostRenderer{} // Create a chart with invalid YAML that would cause AnnotateAndMerge to fail ch := &chart.Chart{ Metadata: &chart.Metadata{ APIVersion: "v1", Name: "test-chart", Version: "0.1.0", }, Templates: []*common.File{ {Name: "templates/invalid", ModTime: time.Now(), Data: []byte("invalid: yaml: content:")}, }, } values := map[string]interface{}{} _, _, _, err := cfg.renderResources( ch, values, "test-release", "", false, false, false, mockPR, false, false, false, ) assert.Error(t, err) assert.Contains(t, err.Error(), "error merging manifests") } func TestRenderResources_PostRenderer_SplitError(t *testing.T) { cfg := actionConfigFixture(t) // Create a post-renderer that returns invalid YAML mockPR := &mockPostRenderer{ transform: func(_ string) string { return "invalid: yaml: content:" }, } ch := buildChart(withSampleTemplates()) values := map[string]interface{}{} _, _, _, err := cfg.renderResources( ch, values, "test-release", "", false, false, false, mockPR, false, false, false, ) assert.Error(t, err) assert.Contains(t, err.Error(), "error while parsing post rendered output: error parsing YAML: MalformedYAMLError:") } func TestRenderResources_PostRenderer_Integration(t *testing.T) { cfg := actionConfigFixture(t) mockPR := &mockPostRenderer{ transform: func(content string) string { return strings.ReplaceAll(content, "metadata:", "color: blue\nmetadata:") }, } ch := buildChart(withSampleTemplates()) values := map[string]interface{}{} hooks, buf, notes, err := cfg.renderResources( ch, values, "test-release", "", false, false, false, mockPR, false, false, false, ) assert.NoError(t, err) assert.NotNil(t, hooks) assert.NotNil(t, buf) assert.Equal(t, "", notes) // Notes should be empty for this test // Verify that the post-renderer modifications are present in the output output := buf.String() expected := `--- # Source: hello/templates/goodbye goodbye: world color: blue --- # Source: hello/templates/hello hello: world color: blue --- # Source: hello/templates/with-partials hello: Earth color: blue ` assert.Contains(t, output, "color: blue") assert.Equal(t, 3, strings.Count(output, "color: blue")) assert.Equal(t, expected, output) } func TestRenderResources_NoPostRenderer(t *testing.T) { cfg := actionConfigFixture(t) ch := buildChart(withSampleTemplates()) values := map[string]interface{}{} hooks, buf, notes, err := cfg.renderResources( ch, values, "test-release", "", false, false, false, nil, false, false, false, ) assert.NoError(t, err) assert.NotNil(t, hooks) assert.NotNil(t, buf) assert.Equal(t, "", notes) } func TestDetermineReleaseSSAApplyMethod(t *testing.T) { assert.Equal(t, release.ApplyMethodClientSideApply, determineReleaseSSApplyMethod(false)) assert.Equal(t, release.ApplyMethodServerSideApply, determineReleaseSSApplyMethod(true)) } func TestIsDryRun(t *testing.T) { assert.False(t, isDryRun(DryRunNone)) assert.True(t, isDryRun(DryRunClient)) assert.True(t, isDryRun(DryRunServer)) } func TestInteractWithServer(t *testing.T) { assert.True(t, interactWithServer(DryRunNone)) assert.False(t, interactWithServer(DryRunClient)) assert.True(t, interactWithServer(DryRunServer)) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/resource_policy.go
pkg/action/resource_policy.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package action import ( "strings" "helm.sh/helm/v4/pkg/kube" releaseutil "helm.sh/helm/v4/pkg/release/v1/util" ) func filterManifestsToKeep(manifests []releaseutil.Manifest) (keep, remaining []releaseutil.Manifest) { for _, m := range manifests { if m.Head.Metadata == nil || m.Head.Metadata.Annotations == nil || len(m.Head.Metadata.Annotations) == 0 { remaining = append(remaining, m) continue } resourcePolicyType, ok := m.Head.Metadata.Annotations[kube.ResourcePolicyAnno] if !ok { remaining = append(remaining, m) continue } resourcePolicyType = strings.ToLower(strings.TrimSpace(resourcePolicyType)) if resourcePolicyType == kube.KeepPolicy { keep = append(keep, m) } } return keep, remaining }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/get_metadata_test.go
pkg/action/get_metadata_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package action import ( "errors" "io" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ci "helm.sh/helm/v4/pkg/chart" chart "helm.sh/helm/v4/pkg/chart/v2" kubefake "helm.sh/helm/v4/pkg/kube/fake" "helm.sh/helm/v4/pkg/release/common" release "helm.sh/helm/v4/pkg/release/v1" ) func TestNewGetMetadata(t *testing.T) { cfg := actionConfigFixture(t) client := NewGetMetadata(cfg) assert.NotNil(t, client) assert.Equal(t, cfg, client.cfg) assert.Equal(t, 0, client.Version) } func TestGetMetadata_Run_BasicMetadata(t *testing.T) { cfg := actionConfigFixture(t) client := NewGetMetadata(cfg) releaseName := "test-release" deployedTime := time.Now() rel := &release.Release{ Name: releaseName, Info: &release.Info{ Status: common.StatusDeployed, LastDeployed: deployedTime, }, Chart: &chart.Chart{ Metadata: &chart.Metadata{ Name: "test-chart", Version: "1.0.0", AppVersion: "v1.2.3", }, }, Version: 1, Namespace: "default", } err := cfg.Releases.Create(rel) require.NoError(t, err) result, err := client.Run(releaseName) require.NoError(t, err) assert.Equal(t, releaseName, result.Name) assert.Equal(t, "test-chart", result.Chart) assert.Equal(t, "1.0.0", result.Version) assert.Equal(t, "v1.2.3", result.AppVersion) assert.Equal(t, "default", result.Namespace) assert.Equal(t, 1, result.Revision) assert.Equal(t, "deployed", result.Status) assert.Equal(t, deployedTime.Format(time.RFC3339), result.DeployedAt) assert.Empty(t, result.Dependencies) assert.Empty(t, result.Annotations) } func TestGetMetadata_Run_WithDependencies(t *testing.T) { cfg := actionConfigFixture(t) client := NewGetMetadata(cfg) releaseName := "test-release" deployedTime := time.Now() dependencies := []*chart.Dependency{ { Name: "mysql", Version: "8.0.25", Repository: "https://charts.bitnami.com/bitnami", }, { Name: "redis", Version: "6.2.4", Repository: "https://charts.bitnami.com/bitnami", }, } rel := &release.Release{ Name: releaseName, Info: &release.Info{ Status: common.StatusDeployed, LastDeployed: deployedTime, }, Chart: &chart.Chart{ Metadata: &chart.Metadata{ Name: "test-chart", Version: "1.0.0", AppVersion: "v1.2.3", Dependencies: dependencies, }, }, Version: 1, Namespace: "default", } require.NoError(t, cfg.Releases.Create(rel)) result, err := client.Run(releaseName) require.NoError(t, err) dep0, err := ci.NewDependencyAccessor(result.Dependencies[0]) require.NoError(t, err) dep1, err := ci.NewDependencyAccessor(result.Dependencies[1]) require.NoError(t, err) assert.Equal(t, releaseName, result.Name) assert.Equal(t, "test-chart", result.Chart) assert.Equal(t, "1.0.0", result.Version) assert.Equal(t, convertDeps(dependencies), result.Dependencies) assert.Len(t, result.Dependencies, 2) assert.Equal(t, "mysql", dep0.Name()) assert.Equal(t, "redis", dep1.Name()) } func TestGetMetadata_Run_WithDependenciesAliases(t *testing.T) { cfg := actionConfigFixture(t) client := NewGetMetadata(cfg) releaseName := "test-release" deployedTime := time.Now() dependencies := []*chart.Dependency{ { Name: "mysql", Version: "8.0.25", Repository: "https://charts.bitnami.com/bitnami", Alias: "database", }, { Name: "redis", Version: "6.2.4", Repository: "https://charts.bitnami.com/bitnami", Alias: "cache", }, } rel := &release.Release{ Name: releaseName, Info: &release.Info{ Status: common.StatusDeployed, LastDeployed: deployedTime, }, Chart: &chart.Chart{ Metadata: &chart.Metadata{ Name: "test-chart", Version: "1.0.0", AppVersion: "v1.2.3", Dependencies: dependencies, }, }, Version: 1, Namespace: "default", } require.NoError(t, cfg.Releases.Create(rel)) result, err := client.Run(releaseName) require.NoError(t, err) dep0, err := ci.NewDependencyAccessor(result.Dependencies[0]) require.NoError(t, err) dep1, err := ci.NewDependencyAccessor(result.Dependencies[1]) require.NoError(t, err) assert.Equal(t, releaseName, result.Name) assert.Equal(t, "test-chart", result.Chart) assert.Equal(t, "1.0.0", result.Version) assert.Equal(t, convertDeps(dependencies), result.Dependencies) assert.Len(t, result.Dependencies, 2) assert.Equal(t, "mysql", dep0.Name()) assert.Equal(t, "database", dep0.Alias()) assert.Equal(t, "redis", dep1.Name()) assert.Equal(t, "cache", dep1.Alias()) } func TestGetMetadata_Run_WithMixedDependencies(t *testing.T) { cfg := actionConfigFixture(t) client := NewGetMetadata(cfg) releaseName := "test-release" deployedTime := time.Now() dependencies := []*chart.Dependency{ { Name: "mysql", Version: "8.0.25", Repository: "https://charts.bitnami.com/bitnami", Alias: "database", }, { Name: "nginx", Version: "1.20.0", Repository: "https://charts.bitnami.com/bitnami", }, { Name: "redis", Version: "6.2.4", Repository: "https://charts.bitnami.com/bitnami", Alias: "cache", }, { Name: "postgresql", Version: "11.0.0", Repository: "https://charts.bitnami.com/bitnami", }, } rel := &release.Release{ Name: releaseName, Info: &release.Info{ Status: common.StatusDeployed, LastDeployed: deployedTime, }, Chart: &chart.Chart{ Metadata: &chart.Metadata{ Name: "test-chart", Version: "1.0.0", AppVersion: "v1.2.3", Dependencies: dependencies, }, }, Version: 1, Namespace: "default", } require.NoError(t, cfg.Releases.Create(rel)) result, err := client.Run(releaseName) require.NoError(t, err) dep0, err := ci.NewDependencyAccessor(result.Dependencies[0]) require.NoError(t, err) dep1, err := ci.NewDependencyAccessor(result.Dependencies[1]) require.NoError(t, err) dep2, err := ci.NewDependencyAccessor(result.Dependencies[2]) require.NoError(t, err) dep3, err := ci.NewDependencyAccessor(result.Dependencies[3]) require.NoError(t, err) assert.Equal(t, releaseName, result.Name) assert.Equal(t, "test-chart", result.Chart) assert.Equal(t, "1.0.0", result.Version) assert.Equal(t, convertDeps(dependencies), result.Dependencies) assert.Len(t, result.Dependencies, 4) // Verify dependencies with aliases assert.Equal(t, "mysql", dep0.Name()) assert.Equal(t, "database", dep0.Alias()) assert.Equal(t, "redis", dep2.Name()) assert.Equal(t, "cache", dep2.Alias()) // Verify dependencies without aliases assert.Equal(t, "nginx", dep1.Name()) assert.Equal(t, "", dep1.Alias()) assert.Equal(t, "postgresql", dep3.Name()) assert.Equal(t, "", dep3.Alias()) } func TestGetMetadata_Run_WithAnnotations(t *testing.T) { cfg := actionConfigFixture(t) client := NewGetMetadata(cfg) releaseName := "test-release" deployedTime := time.Now() annotations := map[string]string{ "helm.sh/hook": "pre-install", "helm.sh/hook-weight": "5", "custom.annotation": "test-value", } rel := &release.Release{ Name: releaseName, Info: &release.Info{ Status: common.StatusDeployed, LastDeployed: deployedTime, }, Chart: &chart.Chart{ Metadata: &chart.Metadata{ Name: "test-chart", Version: "1.0.0", AppVersion: "v1.2.3", Annotations: annotations, }, }, Version: 1, Namespace: "default", } require.NoError(t, cfg.Releases.Create(rel)) result, err := client.Run(releaseName) require.NoError(t, err) assert.Equal(t, releaseName, result.Name) assert.Equal(t, "test-chart", result.Chart) assert.Equal(t, annotations, result.Annotations) assert.Equal(t, "pre-install", result.Annotations["helm.sh/hook"]) assert.Equal(t, "5", result.Annotations["helm.sh/hook-weight"]) assert.Equal(t, "test-value", result.Annotations["custom.annotation"]) } func TestGetMetadata_Run_SpecificVersion(t *testing.T) { cfg := actionConfigFixture(t) client := NewGetMetadata(cfg) client.Version = 2 releaseName := "test-release" deployedTime := time.Now() rel1 := &release.Release{ Name: releaseName, Info: &release.Info{ Status: common.StatusSuperseded, LastDeployed: deployedTime.Add(-time.Hour), }, Chart: &chart.Chart{ Metadata: &chart.Metadata{ Name: "test-chart", Version: "1.0.0", AppVersion: "v1.0.0", }, }, Version: 1, Namespace: "default", } rel2 := &release.Release{ Name: releaseName, Info: &release.Info{ Status: common.StatusDeployed, LastDeployed: deployedTime, }, Chart: &chart.Chart{ Metadata: &chart.Metadata{ Name: "test-chart", Version: "1.1.0", AppVersion: "v1.1.0", }, }, Version: 2, Namespace: "default", } require.NoError(t, cfg.Releases.Create(rel1)) require.NoError(t, cfg.Releases.Create(rel2)) result, err := client.Run(releaseName) require.NoError(t, err) assert.Equal(t, releaseName, result.Name) assert.Equal(t, "test-chart", result.Chart) assert.Equal(t, "1.1.0", result.Version) assert.Equal(t, "v1.1.0", result.AppVersion) assert.Equal(t, 2, result.Revision) assert.Equal(t, "deployed", result.Status) } func TestGetMetadata_Run_DifferentStatuses(t *testing.T) { cfg := actionConfigFixture(t) client := NewGetMetadata(cfg) testCases := []struct { name string status common.Status expected string }{ {"deployed", common.StatusDeployed, "deployed"}, {"failed", common.StatusFailed, "failed"}, {"uninstalled", common.StatusUninstalled, "uninstalled"}, {"pending-install", common.StatusPendingInstall, "pending-install"}, {"pending-upgrade", common.StatusPendingUpgrade, "pending-upgrade"}, {"pending-rollback", common.StatusPendingRollback, "pending-rollback"}, {"superseded", common.StatusSuperseded, "superseded"}, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { releaseName := "test-release-" + tc.name deployedTime := time.Now() rel := &release.Release{ Name: releaseName, Info: &release.Info{ Status: tc.status, LastDeployed: deployedTime, }, Chart: &chart.Chart{ Metadata: &chart.Metadata{ Name: "test-chart", Version: "1.0.0", AppVersion: "v1.0.0", }, }, Version: 1, Namespace: "default", } require.NoError(t, cfg.Releases.Create(rel)) result, err := client.Run(releaseName) require.NoError(t, err) assert.Equal(t, tc.expected, result.Status) }) } } func TestGetMetadata_Run_UnreachableKubeClient(t *testing.T) { cfg := actionConfigFixture(t) failingKubeClient := kubefake.FailingKubeClient{PrintingKubeClient: kubefake.PrintingKubeClient{Out: io.Discard}, DummyResources: nil} failingKubeClient.ConnectionError = errors.New("connection refused") cfg.KubeClient = &failingKubeClient client := NewGetMetadata(cfg) _, err := client.Run("test-release") assert.Error(t, err) assert.Contains(t, err.Error(), "connection refused") } func TestGetMetadata_Run_ReleaseNotFound(t *testing.T) { cfg := actionConfigFixture(t) client := NewGetMetadata(cfg) _, err := client.Run("non-existent-release") assert.Error(t, err) assert.Contains(t, err.Error(), "not found") } func TestGetMetadata_Run_EmptyAppVersion(t *testing.T) { cfg := actionConfigFixture(t) client := NewGetMetadata(cfg) releaseName := "test-release" deployedTime := time.Now() rel := &release.Release{ Name: releaseName, Info: &release.Info{ Status: common.StatusDeployed, LastDeployed: deployedTime, }, Chart: &chart.Chart{ Metadata: &chart.Metadata{ Name: "test-chart", Version: "1.0.0", AppVersion: "", // Empty app version }, }, Version: 1, Namespace: "default", } require.NoError(t, cfg.Releases.Create(rel)) result, err := client.Run(releaseName) require.NoError(t, err) assert.Equal(t, "", result.AppVersion) } func TestMetadata_FormattedDepNames(t *testing.T) { testCases := []struct { name string dependencies []*chart.Dependency expected string }{ { name: "no dependencies", dependencies: []*chart.Dependency{}, expected: "", }, { name: "single dependency", dependencies: []*chart.Dependency{ {Name: "mysql"}, }, expected: "mysql", }, { name: "multiple dependencies sorted", dependencies: []*chart.Dependency{ {Name: "redis"}, {Name: "mysql"}, {Name: "nginx"}, }, expected: "mysql,nginx,redis", }, { name: "already sorted dependencies", dependencies: []*chart.Dependency{ {Name: "apache"}, {Name: "mysql"}, {Name: "zookeeper"}, }, expected: "apache,mysql,zookeeper", }, { name: "duplicate names", dependencies: []*chart.Dependency{ {Name: "mysql"}, {Name: "redis"}, {Name: "mysql"}, }, expected: "mysql,mysql,redis", }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { deps := convertDeps(tc.dependencies) metadata := &Metadata{ Dependencies: deps, } result := metadata.FormattedDepNames() assert.Equal(t, tc.expected, result) }) } } func convertDeps(deps []*chart.Dependency) []ci.Dependency { var newDeps = make([]ci.Dependency, len(deps)) for i, c := range deps { newDeps[i] = c } return newDeps } func TestMetadata_FormattedDepNames_WithComplexDependencies(t *testing.T) { dependencies := []*chart.Dependency{ { Name: "zookeeper", Version: "10.0.0", Repository: "https://charts.bitnami.com/bitnami", Condition: "zookeeper.enabled", }, { Name: "apache", Version: "9.0.0", Repository: "https://charts.bitnami.com/bitnami", }, { Name: "mysql", Version: "8.0.25", Repository: "https://charts.bitnami.com/bitnami", Condition: "mysql.enabled", }, } deps := convertDeps(dependencies) metadata := &Metadata{ Dependencies: deps, } result := metadata.FormattedDepNames() assert.Equal(t, "apache,mysql,zookeeper", result) } func TestMetadata_FormattedDepNames_WithAliases(t *testing.T) { testCases := []struct { name string dependencies []*chart.Dependency expected string }{ { name: "dependencies with aliases", dependencies: []*chart.Dependency{ {Name: "mysql", Alias: "database"}, {Name: "redis", Alias: "cache"}, }, expected: "mysql,redis", }, { name: "mixed dependencies with and without aliases", dependencies: []*chart.Dependency{ {Name: "mysql", Alias: "database"}, {Name: "nginx"}, {Name: "redis", Alias: "cache"}, }, expected: "mysql,nginx,redis", }, { name: "empty alias should use name", dependencies: []*chart.Dependency{ {Name: "mysql", Alias: ""}, {Name: "redis", Alias: "cache"}, }, expected: "mysql,redis", }, { name: "sorted by name not alias", dependencies: []*chart.Dependency{ {Name: "zookeeper", Alias: "a-service"}, {Name: "apache", Alias: "z-service"}, }, expected: "apache,zookeeper", }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { deps := convertDeps(tc.dependencies) metadata := &Metadata{ Dependencies: deps, } result := metadata.FormattedDepNames() assert.Equal(t, tc.expected, result) }) } } func TestGetMetadata_Labels(t *testing.T) { rel := releaseStub() rel.Info.Status = common.StatusDeployed customLabels := map[string]string{"key1": "value1", "key2": "value2"} rel.Labels = customLabels metaGetter := NewGetMetadata(actionConfigFixture(t)) err := metaGetter.cfg.Releases.Create(rel) assert.NoError(t, err) metadata, err := metaGetter.Run(rel.Name) assert.NoError(t, err) assert.Equal(t, metadata.Name, rel.Name) assert.Equal(t, metadata.Labels, customLabels) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/install.go
pkg/action/install.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package action import ( "bytes" "context" "errors" "fmt" "io" "io/fs" "log/slog" "net/url" "os" "path/filepath" "strings" "sync" "sync/atomic" "text/template" "time" "github.com/Masterminds/sprig/v3" v1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/cli-runtime/pkg/resource" "sigs.k8s.io/yaml" ci "helm.sh/helm/v4/pkg/chart" "helm.sh/helm/v4/pkg/chart/common" "helm.sh/helm/v4/pkg/chart/common/util" chart "helm.sh/helm/v4/pkg/chart/v2" chartutil "helm.sh/helm/v4/pkg/chart/v2/util" "helm.sh/helm/v4/pkg/cli" "helm.sh/helm/v4/pkg/downloader" "helm.sh/helm/v4/pkg/getter" "helm.sh/helm/v4/pkg/kube" kubefake "helm.sh/helm/v4/pkg/kube/fake" "helm.sh/helm/v4/pkg/postrenderer" "helm.sh/helm/v4/pkg/registry" ri "helm.sh/helm/v4/pkg/release" rcommon "helm.sh/helm/v4/pkg/release/common" release "helm.sh/helm/v4/pkg/release/v1" releaseutil "helm.sh/helm/v4/pkg/release/v1/util" "helm.sh/helm/v4/pkg/repo/v1" "helm.sh/helm/v4/pkg/storage" "helm.sh/helm/v4/pkg/storage/driver" ) // notesFileSuffix that we want to treat specially. It goes through the templating engine // 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 // since there can be filepath in front of it. const notesFileSuffix = "NOTES.txt" const defaultDirectoryPermission = 0755 // Install performs an installation operation. type Install struct { cfg *Configuration ChartPathOptions // ForceReplace will, if set to `true`, ignore certain warnings and perform the install anyway. // // This should be used with caution. ForceReplace bool // ForceConflicts causes server-side apply to force conflicts ("Overwrite value, become sole manager") // see: https://kubernetes.io/docs/reference/using-api/server-side-apply/#conflicts ForceConflicts bool // ServerSideApply when true (default) will enable changes to be applied via Kubernetes server-side apply // see: https://kubernetes.io/docs/reference/using-api/server-side-apply/ ServerSideApply bool CreateNamespace bool // DryRunStrategy can be set to prepare, but not execute the operation and whether or not to interact with the remote cluster DryRunStrategy DryRunStrategy // 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. HideSecret bool DisableHooks bool Replace bool WaitStrategy kube.WaitStrategy WaitForJobs bool Devel bool DependencyUpdate bool Timeout time.Duration Namespace string ReleaseName string GenerateName bool NameTemplate string Description string OutputDir string // RollbackOnFailure enables rolling back (uninstalling) the release on failure if set RollbackOnFailure bool SkipCRDs bool SubNotes bool HideNotes bool SkipSchemaValidation bool DisableOpenAPIValidation bool IncludeCRDs bool Labels map[string]string // KubeVersion allows specifying a custom kubernetes version to use and // APIVersions allows a manual set of supported API Versions to be passed // (for things like templating). KubeVersion *common.KubeVersion APIVersions common.VersionSet // Used by helm template to render charts with .Release.IsUpgrade. Ignored if Dry-Run is false IsUpgrade bool // Enable DNS lookups when rendering templates EnableDNS bool // Used by helm template to add the release as part of OutputDir path // OutputDir/<ReleaseName> UseReleaseName bool // TakeOwnership will ignore the check for helm annotations and take ownership of the resources. TakeOwnership bool PostRenderer postrenderer.PostRenderer // Lock to control raceconditions when the process receives a SIGTERM Lock sync.Mutex goroutineCount atomic.Int32 } // ChartPathOptions captures common options used for controlling chart paths type ChartPathOptions struct { CaFile string // --ca-file CertFile string // --cert-file KeyFile string // --key-file InsecureSkipTLSVerify bool // --insecure-skip-verify PlainHTTP bool // --plain-http Keyring string // --keyring Password string // --password PassCredentialsAll bool // --pass-credentials RepoURL string // --repo Username string // --username Verify bool // --verify Version string // --version // registryClient provides a registry client but is not added with // options from a flag registryClient *registry.Client } // NewInstall creates a new Install object with the given configuration. func NewInstall(cfg *Configuration) *Install { in := &Install{ cfg: cfg, ServerSideApply: true, DryRunStrategy: DryRunNone, } in.registryClient = cfg.RegistryClient return in } // SetRegistryClient sets the registry client for the install action func (i *Install) SetRegistryClient(registryClient *registry.Client) { i.registryClient = registryClient } // GetRegistryClient get the registry client. func (i *Install) GetRegistryClient() *registry.Client { return i.registryClient } func (i *Install) installCRDs(crds []chart.CRD) error { // We do these one file at a time in the order they were read. totalItems := []*resource.Info{} for _, obj := range crds { // Read in the resources res, err := i.cfg.KubeClient.Build(bytes.NewBuffer(obj.File.Data), false) if err != nil { return fmt.Errorf("failed to install CRD %s: %w", obj.Name, err) } // Send them to Kube if _, err := i.cfg.KubeClient.Create( res, kube.ClientCreateOptionServerSideApply(i.ServerSideApply, i.ForceConflicts)); err != nil { // If the error is CRD already exists, continue. if apierrors.IsAlreadyExists(err) { crdName := obj.Name i.cfg.Logger().Debug("CRD is already present. Skipping", "crd", crdName) continue } return fmt.Errorf("failed to install CRD %s: %w", obj.Name, err) } totalItems = append(totalItems, res...) } if len(totalItems) > 0 { waiter, err := i.cfg.KubeClient.GetWaiter(i.WaitStrategy) if err != nil { return fmt.Errorf("unable to get waiter: %w", err) } // Give time for the CRD to be recognized. if err := waiter.Wait(totalItems, 60*time.Second); err != nil { return err } // If we have already gathered the capabilities, we need to invalidate // the cache so that the new CRDs are recognized. This should only be // the case when an action configuration is reused for multiple actions, // as otherwise it is later loaded by ourselves when getCapabilities // is called later on in the installation process. if i.cfg.Capabilities != nil { discoveryClient, err := i.cfg.RESTClientGetter.ToDiscoveryClient() if err != nil { return err } i.cfg.Logger().Debug("clearing discovery cache") discoveryClient.Invalidate() _, _ = discoveryClient.ServerGroups() } // Invalidate the REST mapper, since it will not have the new CRDs // present. restMapper, err := i.cfg.RESTClientGetter.ToRESTMapper() if err != nil { return err } if resettable, ok := restMapper.(meta.ResettableRESTMapper); ok { i.cfg.Logger().Debug("clearing REST mapper cache") resettable.Reset() } } return nil } // Run executes the installation // // If DryRun is set to true, this will prepare the release, but not install it func (i *Install) Run(chrt ci.Charter, vals map[string]interface{}) (ri.Releaser, error) { ctx := context.Background() return i.RunWithContext(ctx, chrt, vals) } // RunWithContext executes the installation with Context // // When the task is cancelled through ctx, the function returns and the install // proceeds in the background. func (i *Install) RunWithContext(ctx context.Context, ch ci.Charter, vals map[string]interface{}) (ri.Releaser, error) { var chrt *chart.Chart switch c := ch.(type) { case *chart.Chart: chrt = c case chart.Chart: chrt = &c default: return nil, errors.New("invalid chart apiVersion") } if interactWithServer(i.DryRunStrategy) { if err := i.cfg.KubeClient.IsReachable(); err != nil { i.cfg.Logger().Error(fmt.Sprintf("cluster reachability check failed: %v", err)) return nil, fmt.Errorf("cluster reachability check failed: %w", err) } } // HideSecret must be used with dry run. Otherwise, return an error. if !isDryRun(i.DryRunStrategy) && i.HideSecret { i.cfg.Logger().Error("hiding Kubernetes secrets requires a dry-run mode") return nil, errors.New("hiding Kubernetes secrets requires a dry-run mode") } if err := i.availableName(); err != nil { i.cfg.Logger().Error("release name check failed", slog.Any("error", err)) return nil, fmt.Errorf("release name check failed: %w", err) } if err := chartutil.ProcessDependencies(chrt, vals); err != nil { i.cfg.Logger().Error("chart dependencies processing failed", slog.Any("error", err)) return nil, fmt.Errorf("chart dependencies processing failed: %w", err) } // Pre-install anything in the crd/ directory. We do this before Helm // contacts the upstream server and builds the capabilities object. if crds := chrt.CRDObjects(); interactWithServer(i.DryRunStrategy) && !i.SkipCRDs && len(crds) > 0 { // On dry run, bail here if isDryRun(i.DryRunStrategy) { i.cfg.Logger().Warn("This chart or one of its subcharts contains CRDs. Rendering may fail or contain inaccuracies.") } else if err := i.installCRDs(crds); err != nil { return nil, err } } if !interactWithServer(i.DryRunStrategy) { // Add mock objects in here so it doesn't use Kube API server // NOTE(bacongobbler): used for `helm template` i.cfg.Capabilities = common.DefaultCapabilities.Copy() if i.KubeVersion != nil { i.cfg.Capabilities.KubeVersion = *i.KubeVersion } i.cfg.Capabilities.APIVersions = append(i.cfg.Capabilities.APIVersions, i.APIVersions...) i.cfg.KubeClient = &kubefake.PrintingKubeClient{Out: io.Discard} mem := driver.NewMemory() mem.SetNamespace(i.Namespace) i.cfg.Releases = storage.Init(mem) } else if interactWithServer(i.DryRunStrategy) && len(i.APIVersions) > 0 { i.cfg.Logger().Debug("API Version list given outside of client only mode, this list will be ignored") } // Make sure if RollbackOnFailure is set, that wait is set as well. This makes it so // the user doesn't have to specify both if i.WaitStrategy == kube.HookOnlyStrategy && i.RollbackOnFailure { i.WaitStrategy = kube.StatusWatcherStrategy } caps, err := i.cfg.getCapabilities() if err != nil { return nil, err } // special case for helm template --is-upgrade isUpgrade := i.IsUpgrade && isDryRun(i.DryRunStrategy) options := common.ReleaseOptions{ Name: i.ReleaseName, Namespace: i.Namespace, Revision: 1, IsInstall: !isUpgrade, IsUpgrade: isUpgrade, } valuesToRender, err := util.ToRenderValuesWithSchemaValidation(chrt, vals, options, caps, i.SkipSchemaValidation) if err != nil { return nil, err } if driver.ContainsSystemLabels(i.Labels) { return nil, fmt.Errorf("user supplied labels contains system reserved label name. System labels: %+v", driver.GetSystemLabels()) } rel := i.createRelease(chrt, vals, i.Labels) var manifestDoc *bytes.Buffer rel.Hooks, manifestDoc, rel.Info.Notes, err = i.cfg.renderResources(chrt, valuesToRender, i.ReleaseName, i.OutputDir, i.SubNotes, i.UseReleaseName, i.IncludeCRDs, i.PostRenderer, interactWithServer(i.DryRunStrategy), i.EnableDNS, i.HideSecret) // Even for errors, attach this if available if manifestDoc != nil { rel.Manifest = manifestDoc.String() } // Check error from render if err != nil { rel.SetStatus(rcommon.StatusFailed, fmt.Sprintf("failed to render resource: %s", err.Error())) // Return a release with partial data so that the client can show debugging information. return rel, err } // Mark this release as in-progress rel.SetStatus(rcommon.StatusPendingInstall, "Initial install underway") var toBeAdopted kube.ResourceList resources, err := i.cfg.KubeClient.Build(bytes.NewBufferString(rel.Manifest), !i.DisableOpenAPIValidation) if err != nil { return nil, fmt.Errorf("unable to build kubernetes objects from release manifest: %w", err) } // It is safe to use "forceOwnership" here because these are resources currently rendered by the chart. err = resources.Visit(setMetadataVisitor(rel.Name, rel.Namespace, true)) if err != nil { return nil, err } // Install requires an extra validation step of checking that resources // don't already exist before we actually create resources. If we continue // forward and create the release object with resources that already exist, // we'll end up in a state where we will delete those resources upon // deleting the release because the manifest will be pointing at that // resource if interactWithServer(i.DryRunStrategy) && !isUpgrade && len(resources) > 0 { if i.TakeOwnership { toBeAdopted, err = requireAdoption(resources) } else { toBeAdopted, err = existingResourceConflict(resources, rel.Name, rel.Namespace) } if err != nil { return nil, fmt.Errorf("unable to continue with install: %w", err) } } // Bail out here if it is a dry run if isDryRun(i.DryRunStrategy) { rel.Info.Description = "Dry run complete" return rel, nil } if i.CreateNamespace { ns := &v1.Namespace{ TypeMeta: metav1.TypeMeta{ APIVersion: "v1", Kind: "Namespace", }, ObjectMeta: metav1.ObjectMeta{ Name: i.Namespace, Labels: map[string]string{ "name": i.Namespace, }, }, } buf, err := yaml.Marshal(ns) if err != nil { return nil, err } resourceList, err := i.cfg.KubeClient.Build(bytes.NewBuffer(buf), true) if err != nil { return nil, err } if _, err := i.cfg.KubeClient.Create( resourceList, kube.ClientCreateOptionServerSideApply(i.ServerSideApply, false)); err != nil && !apierrors.IsAlreadyExists(err) { return nil, err } } // If Replace is true, we need to supersede the last release. if i.Replace { if err := i.replaceRelease(rel); err != nil { return nil, err } } // Store the release in history before continuing. We always know that this is a create operation if err := i.cfg.Releases.Create(rel); err != nil { // We could try to recover gracefully here, but since nothing has been installed // yet, this is probably safer than trying to continue when we know storage is // not working. return rel, err } rel, err = i.performInstallCtx(ctx, rel, toBeAdopted, resources) if err != nil { rel, err = i.failRelease(rel, err) } return rel, err } func (i *Install) performInstallCtx(ctx context.Context, rel *release.Release, toBeAdopted kube.ResourceList, resources kube.ResourceList) (*release.Release, error) { type Msg struct { r *release.Release e error } resultChan := make(chan Msg, 1) go func() { i.goroutineCount.Add(1) rel, err := i.performInstall(rel, toBeAdopted, resources) resultChan <- Msg{rel, err} i.goroutineCount.Add(-1) }() select { case <-ctx.Done(): err := ctx.Err() return rel, err case msg := <-resultChan: return msg.r, msg.e } } // getGoroutineCount return the number of running routines func (i *Install) getGoroutineCount() int32 { return i.goroutineCount.Load() } func (i *Install) performInstall(rel *release.Release, toBeAdopted kube.ResourceList, resources kube.ResourceList) (*release.Release, error) { var err error // pre-install hooks if !i.DisableHooks { if err := i.cfg.execHook(rel, release.HookPreInstall, i.WaitStrategy, i.Timeout, i.ServerSideApply); err != nil { return rel, fmt.Errorf("failed pre-install: %s", err) } } // At this point, we can do the install. Note that before we were detecting whether to // do an update, but it's not clear whether we WANT to do an update if the reuse is set // to true, since that is basically an upgrade operation. if len(toBeAdopted) == 0 && len(resources) > 0 { _, err = i.cfg.KubeClient.Create( resources, kube.ClientCreateOptionServerSideApply(i.ServerSideApply, false)) } else if len(resources) > 0 { updateThreeWayMergeForUnstructured := i.TakeOwnership && !i.ServerSideApply // Use three-way merge when taking ownership (and not using server-side apply) _, err = i.cfg.KubeClient.Update( toBeAdopted, resources, kube.ClientUpdateOptionForceReplace(i.ForceReplace), kube.ClientUpdateOptionServerSideApply(i.ServerSideApply, i.ForceConflicts), kube.ClientUpdateOptionThreeWayMergeForUnstructured(updateThreeWayMergeForUnstructured), kube.ClientUpdateOptionUpgradeClientSideFieldManager(true)) } if err != nil { return rel, err } waiter, err := i.cfg.KubeClient.GetWaiter(i.WaitStrategy) if err != nil { return rel, fmt.Errorf("failed to get waiter: %w", err) } if i.WaitForJobs { err = waiter.WaitWithJobs(resources, i.Timeout) } else { err = waiter.Wait(resources, i.Timeout) } if err != nil { return rel, err } if !i.DisableHooks { if err := i.cfg.execHook(rel, release.HookPostInstall, i.WaitStrategy, i.Timeout, i.ServerSideApply); err != nil { return rel, fmt.Errorf("failed post-install: %s", err) } } if len(i.Description) > 0 { rel.SetStatus(rcommon.StatusDeployed, i.Description) } else { rel.SetStatus(rcommon.StatusDeployed, "Install complete") } // This is a tricky case. The release has been created, but the result // cannot be recorded. The truest thing to tell the user is that the // release was created. However, the user will not be able to do anything // further with this release. // // One possible strategy would be to do a timed retry to see if we can get // this stored in the future. if err := i.recordRelease(rel); err != nil { i.cfg.Logger().Error("failed to record the release", slog.Any("error", err)) } return rel, nil } func (i *Install) failRelease(rel *release.Release, err error) (*release.Release, error) { rel.SetStatus(rcommon.StatusFailed, fmt.Sprintf("Release %q failed: %s", i.ReleaseName, err.Error())) if i.RollbackOnFailure { i.cfg.Logger().Debug("install failed and rollback-on-failure is set, uninstalling release", "release", i.ReleaseName) uninstall := NewUninstall(i.cfg) uninstall.DisableHooks = i.DisableHooks uninstall.KeepHistory = false uninstall.Timeout = i.Timeout uninstall.WaitStrategy = i.WaitStrategy if _, uninstallErr := uninstall.Run(i.ReleaseName); uninstallErr != nil { return rel, fmt.Errorf("an error occurred while uninstalling the release. original install error: %w: %w", err, uninstallErr) } return rel, fmt.Errorf("release %s failed, and has been uninstalled due to rollback-on-failure being set: %w", i.ReleaseName, err) } i.recordRelease(rel) // Ignore the error, since we have another error to deal with. return rel, err } // availableName tests whether a name is available // // Roughly, this will return an error if name is // // - empty // - too long // - already in use, and not deleted // - used by a deleted release, and i.Replace is false func (i *Install) availableName() error { start := i.ReleaseName if err := chartutil.ValidateReleaseName(start); err != nil { return fmt.Errorf("release name %q: %w", start, err) } // On dry run, bail here if isDryRun(i.DryRunStrategy) { return nil } h, err := i.cfg.Releases.History(start) if err != nil || len(h) < 1 { return nil } hl, err := releaseListToV1List(h) if err != nil { return err } releaseutil.Reverse(hl, releaseutil.SortByRevision) rel := hl[0] if st := rel.Info.Status; i.Replace && (st == rcommon.StatusUninstalled || st == rcommon.StatusFailed) { return nil } return errors.New("cannot reuse a name that is still in use") } func releaseListToV1List(ls []ri.Releaser) ([]*release.Release, error) { rls := make([]*release.Release, 0, len(ls)) for _, val := range ls { rel, err := releaserToV1Release(val) if err != nil { return nil, err } rls = append(rls, rel) } return rls, nil } func releaseV1ListToReleaserList(ls []*release.Release) ([]ri.Releaser, error) { rls := make([]ri.Releaser, 0, len(ls)) for _, val := range ls { rls = append(rls, val) } return rls, nil } // createRelease creates a new release object func (i *Install) createRelease(chrt *chart.Chart, rawVals map[string]interface{}, labels map[string]string) *release.Release { ts := i.cfg.Now() r := &release.Release{ Name: i.ReleaseName, Namespace: i.Namespace, Chart: chrt, Config: rawVals, Info: &release.Info{ FirstDeployed: ts, LastDeployed: ts, Status: rcommon.StatusUnknown, }, Version: 1, Labels: labels, ApplyMethod: string(determineReleaseSSApplyMethod(i.ServerSideApply)), } return r } // recordRelease with an update operation in case reuse has been set. func (i *Install) recordRelease(r *release.Release) error { // This is a legacy function which has been reduced to a oneliner. Could probably // refactor it out. return i.cfg.Releases.Update(r) } // replaceRelease replaces an older release with this one // // This allows us to reuse names by superseding an existing release with a new one func (i *Install) replaceRelease(rel *release.Release) error { hist, err := i.cfg.Releases.History(rel.Name) if err != nil || len(hist) == 0 { // No releases exist for this name, so we can return early return nil } hl, err := releaseListToV1List(hist) if err != nil { return err } releaseutil.Reverse(hl, releaseutil.SortByRevision) last := hl[0] // Update version to the next available rel.Version = last.Version + 1 // Do not change the status of a failed release. if last.Info.Status == rcommon.StatusFailed { return nil } // For any other status, mark it as superseded and store the old record last.SetStatus(rcommon.StatusSuperseded, "superseded by new release") return i.recordRelease(last) } // write the <data> to <output-dir>/<name>. <appendData> controls if the file is created or content will be appended func writeToFile(outputDir string, name string, data string, appendData bool) error { outfileName := strings.Join([]string{outputDir, name}, string(filepath.Separator)) err := ensureDirectoryForFile(outfileName) if err != nil { return err } f, err := createOrOpenFile(outfileName, appendData) if err != nil { return err } defer f.Close() _, err = fmt.Fprintf(f, "---\n# Source: %s\n%s\n", name, data) if err != nil { return err } fmt.Printf("wrote %s\n", outfileName) return nil } func createOrOpenFile(filename string, appendData bool) (*os.File, error) { if appendData { return os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0600) } return os.Create(filename) } // check if the directory exists to create file. creates if doesn't exist func ensureDirectoryForFile(file string) error { baseDir := filepath.Dir(file) _, err := os.Stat(baseDir) if err != nil && !errors.Is(err, fs.ErrNotExist) { return err } return os.MkdirAll(baseDir, defaultDirectoryPermission) } // NameAndChart returns the name and chart that should be used. // // This will read the flags and handle name generation if necessary. func (i *Install) NameAndChart(args []string) (string, string, error) { flagsNotSet := func() error { if i.GenerateName { return errors.New("cannot set --generate-name and also specify a name") } if i.NameTemplate != "" { return errors.New("cannot set --name-template and also specify a name") } return nil } if len(args) > 2 { return args[0], args[1], fmt.Errorf("expected at most two arguments, unexpected arguments: %v", strings.Join(args[2:], ", ")) } if len(args) == 2 { return args[0], args[1], flagsNotSet() } if i.NameTemplate != "" { name, err := TemplateName(i.NameTemplate) return name, args[0], err } if i.ReleaseName != "" { return i.ReleaseName, args[0], nil } if !i.GenerateName { return "", args[0], errors.New("must either provide a name or specify --generate-name") } base := filepath.Base(args[0]) if base == "." || base == "" { base = "chart" } // if present, strip out the file extension from the name if idx := strings.Index(base, "."); idx != -1 { base = base[0:idx] } return fmt.Sprintf("%s-%d", base, time.Now().Unix()), args[0], nil } // TemplateName renders a name template, returning the name or an error. func TemplateName(nameTemplate string) (string, error) { if nameTemplate == "" { return "", nil } t, err := template.New("name-template").Funcs(sprig.TxtFuncMap()).Parse(nameTemplate) if err != nil { return "", err } var b bytes.Buffer if err := t.Execute(&b, nil); err != nil { return "", err } return b.String(), nil } // CheckDependencies checks the dependencies for a chart. func CheckDependencies(ch ci.Charter, reqs []ci.Dependency) error { ac, err := ci.NewAccessor(ch) if err != nil { return err } var missing []string OUTER: for _, r := range reqs { rac, err := ci.NewDependencyAccessor(r) if err != nil { return err } for _, d := range ac.Dependencies() { dac, err := ci.NewAccessor(d) if err != nil { return err } if dac.Name() == rac.Name() { continue OUTER } } missing = append(missing, rac.Name()) } if len(missing) > 0 { return fmt.Errorf("found in Chart.yaml, but missing in charts/ directory: %s", strings.Join(missing, ", ")) } return nil } func portOrDefault(u *url.URL) string { if p := u.Port(); p != "" { return p } switch u.Scheme { case "http": return "80" case "https": return "443" default: return "" } } func urlEqual(u1, u2 *url.URL) bool { return u1.Scheme == u2.Scheme && u1.Hostname() == u2.Hostname() && portOrDefault(u1) == portOrDefault(u2) } // LocateChart looks for a chart directory in known places, and returns either the full path or an error. // // This does not ensure that the chart is well-formed; only that the requested filename exists. // // Order of resolution: // - relative to current working directory when --repo flag is not presented // - if path is absolute or begins with '.', error out here // - URL // // If 'verify' was set on ChartPathOptions, this will attempt to also verify the chart. func (c *ChartPathOptions) LocateChart(name string, settings *cli.EnvSettings) (string, error) { if registry.IsOCI(name) && c.registryClient == nil { return "", fmt.Errorf("unable to lookup chart %q, missing registry client", name) } name = strings.TrimSpace(name) version := strings.TrimSpace(c.Version) if c.RepoURL == "" { if _, err := os.Stat(name); err == nil { abs, err := filepath.Abs(name) if err != nil { return abs, err } if c.Verify { if _, err := downloader.VerifyChart(abs, abs+".prov", c.Keyring); err != nil { return "", err } } return abs, nil } if filepath.IsAbs(name) || strings.HasPrefix(name, ".") { return name, fmt.Errorf("path %q not found", name) } } dl := downloader.ChartDownloader{ Out: os.Stdout, Keyring: c.Keyring, Getters: getter.All(settings), Options: []getter.Option{ getter.WithPassCredentialsAll(c.PassCredentialsAll), getter.WithTLSClientConfig(c.CertFile, c.KeyFile, c.CaFile), getter.WithInsecureSkipVerifyTLS(c.InsecureSkipTLSVerify), getter.WithPlainHTTP(c.PlainHTTP), getter.WithBasicAuth(c.Username, c.Password), }, RepositoryConfig: settings.RepositoryConfig, RepositoryCache: settings.RepositoryCache, ContentCache: settings.ContentCache, RegistryClient: c.registryClient, } if registry.IsOCI(name) { dl.Options = append(dl.Options, getter.WithRegistryClient(c.registryClient)) } if c.Verify { dl.Verify = downloader.VerifyAlways } if c.RepoURL != "" { chartURL, err := repo.FindChartInRepoURL( c.RepoURL, name, getter.All(settings), repo.WithChartVersion(version), repo.WithClientTLS(c.CertFile, c.KeyFile, c.CaFile), repo.WithUsernamePassword(c.Username, c.Password), repo.WithInsecureSkipTLSVerify(c.InsecureSkipTLSVerify), repo.WithPassCredentialsAll(c.PassCredentialsAll), ) if err != nil { return "", err } name = chartURL // Only pass the user/pass on when the user has said to or when the // location of the chart repo and the chart are the same domain. u1, err := url.Parse(c.RepoURL) if err != nil { return "", err } u2, err := url.Parse(chartURL) if err != nil { return "", err } // Host on URL (returned from url.Parse) contains the port if present. // This check ensures credentials are not passed between different // services on different ports. if c.PassCredentialsAll || urlEqual(u1, u2) { dl.Options = append(dl.Options, getter.WithBasicAuth(c.Username, c.Password)) } else { dl.Options = append(dl.Options, getter.WithBasicAuth("", "")) } } else { dl.Options = append(dl.Options, getter.WithBasicAuth(c.Username, c.Password)) } if err := os.MkdirAll(settings.RepositoryCache, 0755); err != nil { return "", err } filename, _, err := dl.DownloadToCache(name, version) if err != nil { return "", err } lname, err := filepath.Abs(filename) if err != nil { return filename, err } return lname, nil }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/status.go
pkg/action/status.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package action import ( "bytes" "helm.sh/helm/v4/pkg/kube" ri "helm.sh/helm/v4/pkg/release" ) // Status is the action for checking the deployment status of releases. // // It provides the implementation of 'helm status'. type Status struct { cfg *Configuration Version int // ShowResourcesTable is used with ShowResources. When true this will cause // the resulting objects to be retrieved as a kind=table. ShowResourcesTable bool } // NewStatus creates a new Status object with the given configuration. func NewStatus(cfg *Configuration) *Status { return &Status{ cfg: cfg, } } // Run executes 'helm status' against the given release. func (s *Status) Run(name string) (ri.Releaser, error) { if err := s.cfg.KubeClient.IsReachable(); err != nil { return nil, err } reli, err := s.cfg.releaseContent(name, s.Version) if err != nil { return nil, err } rel, err := releaserToV1Release(reli) if err != nil { return nil, err } var resources kube.ResourceList if s.ShowResourcesTable { resources, err = s.cfg.KubeClient.BuildTable(bytes.NewBufferString(rel.Manifest), false) if err != nil { return nil, err } } else { resources, err = s.cfg.KubeClient.Build(bytes.NewBufferString(rel.Manifest), false) if err != nil { return nil, err } } resp, err := s.cfg.KubeClient.Get(resources, true) if err != nil { return nil, err } rel.Info.Resources = resp return rel, nil }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/dependency.go
pkg/action/dependency.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package action import ( "fmt" "io" "os" "path/filepath" "strings" "github.com/Masterminds/semver/v3" "github.com/gosuri/uitable" chart "helm.sh/helm/v4/pkg/chart/v2" "helm.sh/helm/v4/pkg/chart/v2/loader" ) // Dependency is the action for building a given chart's dependency tree. // // It provides the implementation of 'helm dependency' and its respective subcommands. type Dependency struct { Verify bool Keyring string SkipRefresh bool ColumnWidth uint Username string Password string CertFile string KeyFile string CaFile string InsecureSkipTLSVerify bool PlainHTTP bool } // NewDependency creates a new Dependency object with the given configuration. func NewDependency() *Dependency { return &Dependency{ ColumnWidth: 80, } } // List executes 'helm dependency list'. func (d *Dependency) List(chartpath string, out io.Writer) error { c, err := loader.Load(chartpath) if err != nil { return err } if c.Metadata.Dependencies == nil { fmt.Fprintf(out, "WARNING: no dependencies at %s\n", filepath.Join(chartpath, "charts")) return nil } d.printDependencies(chartpath, out, c) fmt.Fprintln(out) d.printMissing(chartpath, out, c.Metadata.Dependencies) return nil } // dependencyStatus returns a string describing the status of a dependency viz a viz the parent chart. func (d *Dependency) dependencyStatus(chartpath string, dep *chart.Dependency, parent *chart.Chart) string { filename := fmt.Sprintf("%s-%s.tgz", dep.Name, "*") // If a chart is unpacked, this will check the unpacked chart's `charts/` directory for tarballs. // Technically, this is COMPLETELY unnecessary, and should be removed in Helm 4. It is here // to preserved backward compatibility. In Helm 2/3, there is a "difference" between // the tgz version (which outputs "ok" if it unpacks) and the loaded version (which outputs // "unpacked"). Early in Helm 2's history, this would have made a difference. But it no // longer does. However, since this code shipped with Helm 3, the output must remain stable // until Helm 4. switch archives, err := filepath.Glob(filepath.Join(chartpath, "charts", filename)); { case err != nil: return "bad pattern" case len(archives) > 1: // See if the second part is a SemVer found := []string{} for _, arc := range archives { // we need to trip the prefix dirs and the extension off. filename = strings.TrimSuffix(filepath.Base(arc), ".tgz") maybeVersion := strings.TrimPrefix(filename, fmt.Sprintf("%s-", dep.Name)) if _, err := semver.StrictNewVersion(maybeVersion); err == nil { // If the version parsed without an error, it is possibly a valid // version. found = append(found, arc) } } if l := len(found); l == 1 { // If we get here, we do the same thing as in len(archives) == 1. if r := statArchiveForStatus(found[0], dep); r != "" { return r } // Fall through and look for directories } else if l > 1 { return "too many matches" } // The sanest thing to do here is to fall through and see if we have any directory // matches. case len(archives) == 1: archive := archives[0] if r := statArchiveForStatus(archive, dep); r != "" { return r } } // End unnecessary code. var depChart *chart.Chart for _, item := range parent.Dependencies() { if item.Name() == dep.Name { depChart = item } } if depChart == nil { return "missing" } if depChart.Metadata.Version != dep.Version { constraint, err := semver.NewConstraint(dep.Version) if err != nil { return "invalid version" } v, err := semver.NewVersion(depChart.Metadata.Version) if err != nil { return "invalid version" } if !constraint.Check(v) { return "wrong version" } } return "unpacked" } // stat an archive and return a message if the stat is successful // // This is a refactor of the code originally in dependencyStatus. It is here to // support legacy behavior, and should be removed in Helm 4. func statArchiveForStatus(archive string, dep *chart.Dependency) string { if _, err := os.Stat(archive); err == nil { c, err := loader.Load(archive) if err != nil { return "corrupt" } if c.Name() != dep.Name { return "misnamed" } if c.Metadata.Version != dep.Version { constraint, err := semver.NewConstraint(dep.Version) if err != nil { return "invalid version" } v, err := semver.NewVersion(c.Metadata.Version) if err != nil { return "invalid version" } if !constraint.Check(v) { return "wrong version" } } return "ok" } return "" } // printDependencies prints all of the dependencies in the yaml file. func (d *Dependency) printDependencies(chartpath string, out io.Writer, c *chart.Chart) { table := uitable.New() table.MaxColWidth = d.ColumnWidth table.AddRow("NAME", "VERSION", "REPOSITORY", "STATUS") for _, row := range c.Metadata.Dependencies { table.AddRow(row.Name, row.Version, row.Repository, d.dependencyStatus(chartpath, row, c)) } fmt.Fprintln(out, table) } // printMissing prints warnings about charts that are present on disk, but are // not in Chart.yaml. func (d *Dependency) printMissing(chartpath string, out io.Writer, reqs []*chart.Dependency) { folder := filepath.Join(chartpath, "charts/*") files, err := filepath.Glob(folder) if err != nil { fmt.Fprintln(out, err) return } for _, f := range files { fi, err := os.Stat(f) if err != nil { fmt.Fprintf(out, "Warning: %s\n", err) } // Skip anything that is not a directory and not a tgz file. if !fi.IsDir() && filepath.Ext(f) != ".tgz" { continue } c, err := loader.Load(f) if err != nil { fmt.Fprintf(out, "WARNING: %q is not a chart.\n", f) continue } found := false for _, d := range reqs { if d.Name == c.Name() { found = true break } } if !found { fmt.Fprintf(out, "WARNING: %q is not in Chart.yaml.\n", f) } } }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/registry_login.go
pkg/action/registry_login.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package action import ( "io" "helm.sh/helm/v4/pkg/registry" ) // RegistryLogin performs a registry login operation. type RegistryLogin struct { cfg *Configuration certFile string keyFile string caFile string insecure bool plainHTTP bool } type RegistryLoginOpt func(*RegistryLogin) error // WithCertFile specifies the path to the certificate file to use for TLS. func WithCertFile(certFile string) RegistryLoginOpt { return func(r *RegistryLogin) error { r.certFile = certFile return nil } } // WithInsecure specifies whether to verify certificates. func WithInsecure(insecure bool) RegistryLoginOpt { return func(r *RegistryLogin) error { r.insecure = insecure return nil } } // WithKeyFile specifies the path to the key file to use for TLS. func WithKeyFile(keyFile string) RegistryLoginOpt { return func(r *RegistryLogin) error { r.keyFile = keyFile return nil } } // WithCAFile specifies the path to the CA file to use for TLS. func WithCAFile(caFile string) RegistryLoginOpt { return func(r *RegistryLogin) error { r.caFile = caFile return nil } } // WithPlainHTTPLogin use http rather than https for login. func WithPlainHTTPLogin(isPlain bool) RegistryLoginOpt { return func(r *RegistryLogin) error { r.plainHTTP = isPlain return nil } } // NewRegistryLogin creates a new RegistryLogin object with the given configuration. func NewRegistryLogin(cfg *Configuration) *RegistryLogin { return &RegistryLogin{ cfg: cfg, } } // Run executes the registry login operation func (a *RegistryLogin) Run(_ io.Writer, hostname string, username string, password string, opts ...RegistryLoginOpt) error { for _, opt := range opts { if err := opt(a); err != nil { return err } } return a.cfg.RegistryClient.Login( hostname, registry.LoginOptBasicAuth(username, password), registry.LoginOptInsecure(a.insecure), registry.LoginOptTLSClientConfig(a.certFile, a.keyFile, a.caFile), registry.LoginOptPlainText(a.plainHTTP), ) }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/validate.go
pkg/action/validate.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package action import ( "fmt" "maps" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/runtime" "k8s.io/cli-runtime/pkg/resource" "helm.sh/helm/v4/pkg/kube" ) var accessor = meta.NewAccessor() const ( appManagedByLabel = "app.kubernetes.io/managed-by" appManagedByHelm = "Helm" helmReleaseNameAnnotation = "meta.helm.sh/release-name" helmReleaseNamespaceAnnotation = "meta.helm.sh/release-namespace" ) // requireAdoption returns the subset of resources that already exist in the cluster. func requireAdoption(resources kube.ResourceList) (kube.ResourceList, error) { var requireUpdate kube.ResourceList err := resources.Visit(func(info *resource.Info, err error) error { if err != nil { return err } helper := resource.NewHelper(info.Client, info.Mapping) _, err = helper.Get(info.Namespace, info.Name) if err != nil { if apierrors.IsNotFound(err) { return nil } return fmt.Errorf("could not get information about the resource %s: %w", resourceString(info), err) } infoCopy := *info requireUpdate.Append(&infoCopy) return nil }) return requireUpdate, err } func existingResourceConflict(resources kube.ResourceList, releaseName, releaseNamespace string) (kube.ResourceList, error) { var requireUpdate kube.ResourceList err := resources.Visit(func(info *resource.Info, err error) error { if err != nil { return err } helper := resource.NewHelper(info.Client, info.Mapping) existing, err := helper.Get(info.Namespace, info.Name) if err != nil { if apierrors.IsNotFound(err) { return nil } return fmt.Errorf("could not get information about the resource %s: %w", resourceString(info), err) } // Allow adoption of the resource if it is managed by Helm and is annotated with correct release name and namespace. if err := checkOwnership(existing, releaseName, releaseNamespace); err != nil { return fmt.Errorf("%s exists and cannot be imported into the current release: %s", resourceString(info), err) } infoCopy := *info requireUpdate.Append(&infoCopy) return nil }) return requireUpdate, err } func checkOwnership(obj runtime.Object, releaseName, releaseNamespace string) error { lbls, err := accessor.Labels(obj) if err != nil { return err } annos, err := accessor.Annotations(obj) if err != nil { return err } var errs []error if err := requireValue(lbls, appManagedByLabel, appManagedByHelm); err != nil { errs = append(errs, fmt.Errorf("label validation error: %s", err)) } if err := requireValue(annos, helmReleaseNameAnnotation, releaseName); err != nil { errs = append(errs, fmt.Errorf("annotation validation error: %s", err)) } if err := requireValue(annos, helmReleaseNamespaceAnnotation, releaseNamespace); err != nil { errs = append(errs, fmt.Errorf("annotation validation error: %s", err)) } if len(errs) > 0 { return fmt.Errorf("invalid ownership metadata; %w", joinErrors(errs, "; ")) } return nil } func requireValue(meta map[string]string, k, v string) error { actual, ok := meta[k] if !ok { return fmt.Errorf("missing key %q: must be set to %q", k, v) } if actual != v { return fmt.Errorf("key %q must equal %q: current value is %q", k, v, actual) } return nil } // setMetadataVisitor adds release tracking metadata to all resources. If forceOwnership is enabled, existing // ownership metadata will be overwritten. Otherwise an error will be returned if any resource has an // existing and conflicting value for the managed by label or Helm release/namespace annotations. func setMetadataVisitor(releaseName, releaseNamespace string, forceOwnership bool) resource.VisitorFunc { return func(info *resource.Info, err error) error { if err != nil { return err } if !forceOwnership { if err := checkOwnership(info.Object, releaseName, releaseNamespace); err != nil { return fmt.Errorf("%s cannot be owned: %s", resourceString(info), err) } } if err := mergeLabels(info.Object, map[string]string{ appManagedByLabel: appManagedByHelm, }); err != nil { return fmt.Errorf( "%s labels could not be updated: %s", resourceString(info), err, ) } if err := mergeAnnotations(info.Object, map[string]string{ helmReleaseNameAnnotation: releaseName, helmReleaseNamespaceAnnotation: releaseNamespace, }); err != nil { return fmt.Errorf( "%s annotations could not be updated: %s", resourceString(info), err, ) } return nil } } func resourceString(info *resource.Info) string { _, k := info.Mapping.GroupVersionKind.ToAPIVersionAndKind() return fmt.Sprintf( "%s %q in namespace %q", k, info.Name, info.Namespace, ) } func mergeLabels(obj runtime.Object, labels map[string]string) error { current, err := accessor.Labels(obj) if err != nil { return err } return accessor.SetLabels(obj, mergeStrStrMaps(current, labels)) } func mergeAnnotations(obj runtime.Object, annotations map[string]string) error { current, err := accessor.Annotations(obj) if err != nil { return err } return accessor.SetAnnotations(obj, mergeStrStrMaps(current, annotations)) } // merge two maps, always taking the value on the right func mergeStrStrMaps(current, desired map[string]string) map[string]string { result := make(map[string]string) maps.Copy(result, current) maps.Copy(result, desired) return result }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false
helm/helm
https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/release_testing_test.go
pkg/action/release_testing_test.go
/* Copyright The Helm Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package action import ( "bytes" "errors" "io" "os" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "helm.sh/helm/v4/pkg/cli" kubefake "helm.sh/helm/v4/pkg/kube/fake" release "helm.sh/helm/v4/pkg/release/v1" ) func TestNewReleaseTesting(t *testing.T) { config := actionConfigFixture(t) client := NewReleaseTesting(config) assert.NotNil(t, client) assert.Equal(t, config, client.cfg) } func TestReleaseTestingRun_UnreachableKubeClient(t *testing.T) { config := actionConfigFixture(t) failingKubeClient := kubefake.FailingKubeClient{PrintingKubeClient: kubefake.PrintingKubeClient{Out: io.Discard}, DummyResources: nil} failingKubeClient.ConnectionError = errors.New("connection refused") config.KubeClient = &failingKubeClient client := NewReleaseTesting(config) result, err := client.Run("") assert.Nil(t, result) assert.Error(t, err) } func TestReleaseTestingGetPodLogs_FilterEvents(t *testing.T) { config := actionConfigFixture(t) require.NoError(t, config.Init(cli.New().RESTClientGetter(), "", os.Getenv("HELM_DRIVER"))) client := NewReleaseTesting(config) client.Filters[ExcludeNameFilter] = []string{"event-1"} client.Filters[IncludeNameFilter] = []string{"event-3"} hooks := []*release.Hook{ { Name: "event-1", Events: []release.HookEvent{release.HookTest}, }, { Name: "event-2", Events: []release.HookEvent{release.HookTest}, }, } out := &bytes.Buffer{} require.NoError(t, client.GetPodLogs(out, &release.Release{Hooks: hooks})) assert.Empty(t, out.String()) } func TestReleaseTestingGetPodLogs_PodRetrievalError(t *testing.T) { config := actionConfigFixture(t) require.NoError(t, config.Init(cli.New().RESTClientGetter(), "", os.Getenv("HELM_DRIVER"))) client := NewReleaseTesting(config) hooks := []*release.Hook{ { Name: "event-1", Events: []release.HookEvent{release.HookTest}, }, } require.ErrorContains(t, client.GetPodLogs(&bytes.Buffer{}, &release.Release{Hooks: hooks}), "unable to get pod logs") }
go
Apache-2.0
08f17fc9474ca51006427319bfa35e7630961a70
2026-01-07T08:36:55.903988Z
false