Merge branch 'master' of github.com:helm/helm into validate-signature

pull/7944/head
jdolitsky 5 years ago
commit 2e6d86546a

@ -5,11 +5,11 @@ jobs:
build: build:
working_directory: ~/helm.sh/helm working_directory: ~/helm.sh/helm
docker: docker:
- image: circleci/golang:1.13 - image: circleci/golang:1.14
environment: environment:
GOCACHE: "/tmp/go/cache" GOCACHE: "/tmp/go/cache"
GOLANGCI_LINT_VERSION: "1.21.0" GOLANGCI_LINT_VERSION: "1.27.0"
steps: steps:
- checkout - checkout

@ -0,0 +1,12 @@
<!-- Thanks for sending a pull request! Here are some tips for you:
1. Make sure to read the Contributing Guide before submitting your PR: https://github.com/helm/helm/blob/master/CONTRIBUTING.md
2. If this PR closes another issue, add 'closes #<issue number>' somewhere in the PR summary. GitHub will automatically close that issue when this PR gets merged. Alternatively, adding 'refs #<issue number>' will not close the issue, but help provide the reviewer more context.-->
**What this PR does / why we need it**:
**Special notes for your reviewer**:
**If applicable**:
- [ ] this PR contains documentation
- [ ] this PR contains unit tests
- [ ] this PR has been tested for backwards compatibility

@ -1,21 +1,22 @@
# Contributing Guidelines # Contributing Guidelines
The Helm project accepts contributions via GitHub pull requests. This document outlines the process to help get your contribution accepted. The Helm project accepts contributions via GitHub pull requests. This document outlines the process
to help get your contribution accepted.
## Reporting a Security Issue ## Reporting a Security Issue
Most of the time, when you find a bug in Helm, it should be reported Most of the time, when you find a bug in Helm, it should be reported using [GitHub
using [GitHub issues](https://github.com/helm/helm/issues). However, if issues](https://github.com/helm/helm/issues). However, if you are reporting a _security
you are reporting a _security vulnerability_, please email a report to vulnerability_, please email a report to
[cncf-kubernetes-helm-security@lists.cncf.io](mailto:cncf-kubernetes-helm-security@lists.cncf.io). This will give [cncf-helm-security@lists.cncf.io](mailto:cncf-helm-security@lists.cncf.io). This will give us a
us a chance to try to fix the issue before it is exploited in the wild. chance to try to fix the issue before it is exploited in the wild.
## Sign Your Work ## Sign Your Work
The sign-off is a simple line at the end of the explanation for a commit. All The sign-off is a simple line at the end of the explanation for a commit. All commits needs to be
commits needs to be signed. Your signature certifies that you wrote the patch or signed. Your signature certifies that you wrote the patch or otherwise have the right to contribute
otherwise have the right to contribute the material. The rules are pretty simple, the material. The rules are pretty simple, if you can certify the below (from
if you can certify the below (from [developercertificate.org](https://developercertificate.org/)): [developercertificate.org](https://developercertificate.org/)):
``` ```
Developer Certificate of Origin Developer Certificate of Origin
@ -62,11 +63,11 @@ Then you just add a line to every git commit message:
Use your real name (sorry, no pseudonyms or anonymous contributions.) Use your real name (sorry, no pseudonyms or anonymous contributions.)
If you set your `user.name` and `user.email` git configs, you can sign your If you set your `user.name` and `user.email` git configs, you can sign your commit automatically
commit automatically with `git commit -s`. with `git commit -s`.
Note: If your git config information is set properly then viewing the Note: If your git config information is set properly then viewing the `git log` information for your
`git log` information for your commit will look something like this: commit will look something like this:
``` ```
Author: Joe Smith <joe.smith@example.com> Author: Joe Smith <joe.smith@example.com>
@ -77,8 +78,8 @@ Date: Thu Feb 2 11:41:15 2018 -0800
Signed-off-by: Joe Smith <joe.smith@example.com> Signed-off-by: Joe Smith <joe.smith@example.com>
``` ```
Notice the `Author` and `Signed-off-by` lines match. If they don't Notice the `Author` and `Signed-off-by` lines match. If they don't your PR will be rejected by the
your PR will be rejected by the automated DCO check. automated DCO check.
## Support Channels ## Support Channels
@ -89,49 +90,65 @@ Whether you are a user or contributor, official support channels include:
- User: [#helm-users](https://kubernetes.slack.com/messages/C0NH30761/details/) - User: [#helm-users](https://kubernetes.slack.com/messages/C0NH30761/details/)
- Contributor: [#helm-dev](https://kubernetes.slack.com/messages/C51E88VDG/) - Contributor: [#helm-dev](https://kubernetes.slack.com/messages/C51E88VDG/)
Before opening a new issue or submitting a new pull request, it's helpful to search the project - it's likely that another user has already reported the issue you're facing, or it's a known issue that we're already aware of. It is also worth asking on the Slack channels. Before opening a new issue or submitting a new pull request, it's helpful to search the project -
it's likely that another user has already reported the issue you're facing, or it's a known issue
that we're already aware of. It is also worth asking on the Slack channels.
## Milestones ## Milestones
We use milestones to track progress of releases. There are also 2 special milestones We use milestones to track progress of specific planned releases.
used for helping us keep work organized: `Upcoming - Minor` and `Upcoming - Major`
`Upcoming - Minor` is used for keeping track of issues that aren't assigned to a specific For example, if the latest currently-released version is `3.2.1`, an issue/PR which pertains to a
release but could easily be addressed in a minor release. `Upcoming - Major` keeps track specific upcoming bugfix or feature release could fall into one of two different active milestones:
of issues that will need to be addressed in a major release. For example, if the current `3.2.2` or `3.3.0`.
version is `3.2.0` an issue/PR could fall in to one of 4 different active milestones:
`3.2.1`, `3.3.0`, `Upcoming - Minor`, or `Upcoming - Major`. If an issue pertains to a
specific upcoming bug or minor release, it would go into `3.2.1` or `3.3.0`. If the issue/PR
does not have a specific milestone yet, but it is likely that it will land in a `3.X` release,
it should go into `Upcoming - Minor`. If the issue/PR is a large functionality add or change
and/or it breaks compatibility, then it should be added to the `Upcoming - Major` milestone.
An issue that we are not sure we will be doing will not be added to any milestone.
A milestone (and hence release) is considered done when all outstanding issues/PRs have been closed or moved to another milestone. Issues and PRs which are deemed backwards-incompatible may be added to the discussion items for
Helm 4 with [label:v4.x](https://github.com/helm/helm/labels/v4.x). An issue or PR that we are not
sure we will be addressing will not be added to any milestone.
A milestone (and hence release) can be closed when all outstanding issues/PRs have been closed
or moved to another milestone and the associated release has been published.
## Semantic Versioning ## Semantic Versioning
Helm maintains a strong commitment to backward compatibility. All of our changes to protocols and formats are backward compatible from one major release to the next. No features, flags, or commands are removed or substantially modified (unless we need to fix a security issue). Helm maintains a strong commitment to backward compatibility. All of our changes to protocols and
formats are backward compatible from one major release to the next. No features, flags, or commands
are removed or substantially modified (unless we need to fix a security issue).
We also try very hard to not change publicly accessible Go library definitions inside of the `pkg/` directory of our source code. We also try very hard to not change publicly accessible Go library definitions inside of the `pkg/`
directory of our source code.
For a quick summary of our backward compatibility guidelines for releases between 3.0 and 4.0: For a quick summary of our backward compatibility guidelines for releases between 3.0 and 4.0:
- Command line commands, flags, and arguments MUST be backward compatible - Command line commands, flags, and arguments MUST be backward compatible
- File formats (such as Chart.yaml) MUST be backward compatible - File formats (such as Chart.yaml) MUST be backward compatible
- Any chart that worked on a previous version of Helm 3 MUST work on a new version of Helm 3 (barring the cases where (a) Kubernetes itself changed, and (b) the chart worked because it exploited a bug) - Any chart that worked on a previous version of Helm 3 MUST work on a new version of Helm 3
(barring the cases where (a) Kubernetes itself changed, and (b) the chart worked because it
exploited a bug)
- Chart repository functionality MUST be backward compatible - Chart repository functionality MUST be backward compatible
- Go libraries inside of `pkg/` SHOULD remain backward compatible, though code inside of `cmd/` and `internal/` may be changed from release to release without notice. - Go libraries inside of `pkg/` SHOULD remain backward compatible, though code inside of `cmd/` and
`internal/` may be changed from release to release without notice.
## Support Contract for Helm 2 ## Support Contract for Helm 2
With Helm 2's current release schedule, we want to take into account any migration issues for users due to the upcoming holiday shopping season and tax season. We also want to clarify what actions may occur after the support contract ends for Helm 2, so that users will not be surprised or caught off guard. With Helm 2's current release schedule, we want to take into account any migration issues for users
due to the upcoming holiday shopping season and tax season. We also want to clarify what actions may
occur after the support contract ends for Helm 2, so that users will not be surprised or caught off
guard.
After Helm 2.15.0 is released, Helm 2 will go into "maintenance mode". We will continue to accept bug fixes and fix any security issues that arise, but no new features will be accepted for Helm 2. All feature development will be moved over to Helm 3. After Helm 2.15.0 is released, Helm 2 will go into "maintenance mode". We will continue to accept
bug fixes and fix any security issues that arise, but no new features will be accepted for Helm 2.
All feature development will be moved over to Helm 3.
6 months after Helm 3.0.0's public release, Helm 2 will stop accepting bug fixes. Only security issues will be accepted. 6 months after Helm 3.0.0's public release, Helm 2 will stop accepting bug fixes. Only security
issues will be accepted.
12 months after Helm 3.0.0's public release, support for Helm 2 will formally end. Download links for the Helm 2 client through Google Cloud Storage, the Docker image for Tiller stored in Google Container Registry, and the Google Cloud buckets for the stable and incubator chart repositories may no longer work at any point. Client downloads through `get.helm.sh` will continue to work, and we will distribute a Tiller image that will be made available at an alternative location which can be updated with `helm init --tiller-image`. 12 months after Helm 3.0.0's public release, support for Helm 2 will formally end. Download links
for the Helm 2 client through Google Cloud Storage, the Docker image for Tiller stored in Google
Container Registry, and the Google Cloud buckets for the stable and incubator chart repositories may
no longer work at any point. Client downloads through `get.helm.sh` will continue to work, and we
will distribute a Tiller image that will be made available at an alternative location which can be
updated with `helm init --tiller-image`.
## Issues ## Issues
@ -141,54 +158,56 @@ Issues are used as the primary method for tracking anything to do with the Helm
There are 5 types of issues (each with their own corresponding [label](#labels)): There are 5 types of issues (each with their own corresponding [label](#labels)):
- `question/support`: These are support or functionality inquiries that we want to have a record of for - `question/support`: These are support or functionality inquiries that we want to have a record of
future reference. Generally these are questions that are too complex or large to store in the for future reference. Generally these are questions that are too complex or large to store in the
Slack channel or have particular interest to the community as a whole. Depending on the discussion, Slack channel or have particular interest to the community as a whole. Depending on the
these can turn into `feature` or `bug` issues. discussion, these can turn into `feature` or `bug` issues.
- `proposal`: Used for items (like this one) that propose a new ideas or functionality that require - `proposal`: Used for items (like this one) that propose a new ideas or functionality that require
a larger community discussion. This allows for feedback from others in the community before a a larger community discussion. This allows for feedback from others in the community before a
feature is actually developed. This is not needed for small additions. Final word on whether or feature is actually developed. This is not needed for small additions. Final word on whether or
not a feature needs a proposal is up to the core maintainers. All issues that are proposals should not a feature needs a proposal is up to the core maintainers. All issues that are proposals should
both have a label and an issue title of "Proposal: [the rest of the title]." A proposal can become both have a label and an issue title of "Proposal: [the rest of the title]." A proposal can become
a `feature` and does not require a milestone. a `feature` and does not require a milestone.
- `feature`: These track specific feature requests and ideas until they are complete. They can evolve - `feature`: These track specific feature requests and ideas until they are complete. They can
from a `proposal` or can be submitted individually depending on the size. evolve from a `proposal` or can be submitted individually depending on the size.
- `bug`: These track bugs with the code - `bug`: These track bugs with the code
- `docs`: These track problems with the documentation (i.e. missing or incomplete) - `docs`: These track problems with the documentation (i.e. missing or incomplete)
### Issue Lifecycle ### Issue Lifecycle
The issue lifecycle is mainly driven by the core maintainers, but is good information for those The issue lifecycle is mainly driven by the core maintainers, but is good information for those
contributing to Helm. All issue types follow the same general lifecycle. Differences are noted below. contributing to Helm. All issue types follow the same general lifecycle. Differences are noted
below.
1. Issue creation 1. Issue creation
2. Triage 2. Triage
- The maintainer in charge of triaging will apply the proper labels for the issue. This - The maintainer in charge of triaging will apply the proper labels for the issue. This includes
includes labels for priority, type, and metadata (such as `good first issue`). The only issue labels for priority, type, and metadata (such as `good first issue`). The only issue priority
priority we will be tracking is whether or not the issue is "critical." If additional we will be tracking is whether or not the issue is "critical." If additional levels are needed
levels are needed in the future, we will add them. in the future, we will add them.
- (If needed) Clean up the title to succinctly and clearly state the issue. Also ensure - (If needed) Clean up the title to succinctly and clearly state the issue. Also ensure that
that proposals are prefaced with "Proposal: [the rest of the title]". proposals are prefaced with "Proposal: [the rest of the title]".
- Add the issue to the correct milestone. If any questions come up, don't worry about - Add the issue to the correct milestone. If any questions come up, don't worry about adding the
adding the issue to a milestone until the questions are answered. issue to a milestone until the questions are answered.
- We attempt to do this process at least once per work day. - We attempt to do this process at least once per work day.
3. Discussion 3. Discussion
- issues that are labeled as `feature` or `bug` should be connected to the PR that resolves it. - issues that are labeled as `feature` or `bug` should be connected to the PR that resolves it.
- Whoever is working on a `feature` or `bug` issue (whether a maintainer or someone from - Whoever is working on a `feature` or `bug` issue (whether a maintainer or someone from the
the community), should either assign the issue to themself or make a comment in the issue community), should either assign the issue to themself or make a comment in the issue saying
saying that they are taking it. that they are taking it.
- `proposal` and `support/question` issues should stay open until resolved or if they have not been - `proposal` and `support/question` issues should stay open until resolved or if they have not
active for more than 30 days. This will help keep the issue queue to a manageable size and been active for more than 30 days. This will help keep the issue queue to a manageable size
reduce noise. Should the issue need to stay open, the `keep open` label can be added. and reduce noise. Should the issue need to stay open, the `keep open` label can be added.
4. Issue closure 4. Issue closure
## How to Contribute a Patch ## How to Contribute a Patch
1. If you haven't already done so, sign a Contributor License Agreement (see details above). 1. Identify or create the related issue.
2. Fork the desired repo, develop and test your code changes. 2. Fork the desired repo; develop and test your code changes.
3. Submit a pull request. 3. Submit a pull request, making sure to sign your work and link the related issue.
Coding conventions and standards are explained in the [official developer docs](https://helm.sh/docs/developers/). Coding conventions and standards are explained in the [official developer
docs](https://helm.sh/docs/developers/).
## Pull Requests ## Pull Requests
@ -199,41 +218,42 @@ Like any good open source project, we use Pull Requests (PRs) to track code chan
1. PR creation 1. PR creation
- PRs are usually created to fix or else be a subset of other PRs that fix a particular issue. - PRs are usually created to fix or else be a subset of other PRs that fix a particular issue.
- We more than welcome PRs that are currently in progress. They are a great way to keep track of - We more than welcome PRs that are currently in progress. They are a great way to keep track of
important work that is in-flight, but useful for others to see. If a PR is a work in progress, important work that is in-flight, but useful for others to see. If a PR is a work in progress,
it **must** be prefaced with "WIP: [title]". Once the PR is ready for review, remove "WIP" from it **must** be prefaced with "WIP: [title]". Once the PR is ready for review, remove "WIP"
the title. from the title.
- It is preferred, but not required, to have a PR tied to a specific issue. There can be - It is preferred, but not required, to have a PR tied to a specific issue. There can be
circumstances where if it is a quick fix then an issue might be overkill. The details provided circumstances where if it is a quick fix then an issue might be overkill. The details provided
in the PR description would suffice in this case. in the PR description would suffice in this case.
2. Triage 2. Triage
- The maintainer in charge of triaging will apply the proper labels for the issue. This should - The maintainer in charge of triaging will apply the proper labels for the issue. This should
include at least a size label, `bug` or `feature`, and `awaiting review` once all labels are applied. include at least a size label, `bug` or `feature`, and `awaiting review` once all labels are
See the [Labels section](#labels) for full details on the definitions of labels. applied. See the [Labels section](#labels) for full details on the definitions of labels.
- Add the PR to the correct milestone. This should be the same as the issue the PR closes. - Add the PR to the correct milestone. This should be the same as the issue the PR closes.
3. Assigning reviews 3. Assigning reviews
- Once a review has the `awaiting review` label, maintainers will review them as schedule permits. - Once a review has the `awaiting review` label, maintainers will review them as schedule
The maintainer who takes the issue should self-request a review. permits. The maintainer who takes the issue should self-request a review.
- Any PR with the `size/large` label requires 2 review approvals from maintainers before it can be - Any PR with the `size/large` label requires 2 review approvals from maintainers before it can
merged. Those with `size/medium` or `size/small` are per the judgement of the maintainers. be merged. Those with `size/medium` or `size/small` are per the judgement of the maintainers.
4. Reviewing/Discussion 4. Reviewing/Discussion
- All reviews will be completed using Github review tool. - All reviews will be completed using Github review tool.
- A "Comment" review should be used when there are questions about the code that should be - A "Comment" review should be used when there are questions about the code that should be
answered, but that don't involve code changes. This type of review does not count as approval. answered, but that don't involve code changes. This type of review does not count as approval.
- A "Changes Requested" review indicates that changes to the code need to be made before they will be merged. - A "Changes Requested" review indicates that changes to the code need to be made before they
will be merged.
- Reviewers should update labels as needed (such as `needs rebase`) - Reviewers should update labels as needed (such as `needs rebase`)
5. Address comments by answering questions or changing code 5. Address comments by answering questions or changing code
6. LGTM (Looks good to me) 6. LGTM (Looks good to me)
- Once a Reviewer has completed a review and the code looks ready to merge, an "Approve" review is used - Once a Reviewer has completed a review and the code looks ready to merge, an "Approve" review
to signal to the contributor and to other maintainers that you have reviewed the code and feel that it is is used to signal to the contributor and to other maintainers that you have reviewed the code
ready to be merged. and feel that it is ready to be merged.
7. Merge or close 7. Merge or close
- PRs should stay open until merged or if they have not been active for more than 30 days. - PRs should stay open until merged or if they have not been active for more than 30 days. This
This will help keep the PR queue to a manageable size and reduce noise. Should the PR need will help keep the PR queue to a manageable size and reduce noise. Should the PR need to stay
to stay open (like in the case of a WIP), the `keep open` label can be added. open (like in the case of a WIP), the `keep open` label can be added.
- Before merging a PR, refer to the topic on [Size Labels](#size-labels) below to determine if - Before merging a PR, refer to the topic on [Size Labels](#size-labels) below to determine if
the PR requires more than one LGTM to merge. the PR requires more than one LGTM to merge.
- If the owner of the PR is listed in the `OWNERS` file, that user **must** merge their own PRs - If the owner of the PR is listed in the `OWNERS` file, that user **must** merge their own PRs
or explicitly request another OWNER do that for them. or explicitly request another OWNER do that for them.
- If the owner of a PR is _not_ listed in `OWNERS`, any core maintainer may merge the PR. - If the owner of a PR is _not_ listed in `OWNERS`, any core maintainer may merge the PR.
#### Documentation PRs #### Documentation PRs
@ -286,12 +306,12 @@ The following tables define all label types used for Helm. It is split up by cat
#### Size labels #### Size labels
Size labels are used to indicate how "dangerous" a PR is. The guidelines below are used to assign the Size labels are used to indicate how "dangerous" a PR is. The guidelines below are used to assign
labels, but ultimately this can be changed by the maintainers. For example, even if a PR only makes the labels, but ultimately this can be changed by the maintainers. For example, even if a PR only
30 lines of changes in 1 file, but it changes key functionality, it will likely be labeled as `size/L` makes 30 lines of changes in 1 file, but it changes key functionality, it will likely be labeled as
because it requires sign off from multiple people. Conversely, a PR that adds a small feature, but requires `size/L` because it requires sign off from multiple people. Conversely, a PR that adds a small
another 150 lines of tests to cover all cases, could be labeled as `size/S` even though the number of feature, but requires another 150 lines of tests to cover all cases, could be labeled as `size/S`
lines is greater than defined below. even though the number of lines is greater than defined below.
PRs submitted by a core maintainer, regardless of size, only requires approval from one additional PRs submitted by a core maintainer, regardless of size, only requires approval from one additional
maintainer. This ensures there are at least two maintainers who are aware of any significant PRs maintainer. This ensures there are at least two maintainers who are aware of any significant PRs

@ -5,7 +5,6 @@ TARGET_OBJS ?= darwin-amd64.tar.gz darwin-amd64.tar.gz.sha256 darwin-amd64.tar.g
BINNAME ?= helm BINNAME ?= helm
GOPATH = $(shell go env GOPATH) GOPATH = $(shell go env GOPATH)
DEP = $(GOPATH)/bin/dep
GOX = $(GOPATH)/bin/gox GOX = $(GOPATH)/bin/gox
GOIMPORTS = $(GOPATH)/bin/goimports GOIMPORTS = $(GOPATH)/bin/goimports
ARCH = $(shell uname -p) ARCH = $(shell uname -p)

@ -21,61 +21,70 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"helm.sh/helm/v3/cmd/helm/require"
) )
const completionDesc = ` const completionDesc = `
Generate autocompletions script for Helm for the specified shell (bash or zsh). Generate autocompletions script for Helm for the specified shell.
`
const bashCompDesc = `
Generate the autocompletion script for Helm for the bash shell.
This command can generate shell autocompletions. e.g. To load completions in your current shell session:
$ source <(helm completion bash)
$ 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
`
Can be sourced as such const zshCompDesc = `
Generate the autocompletion script for Helm for the zsh shell.
$ source <(helm completion bash) To load completions in your current shell session:
` $ source <(helm completion zsh)
var ( To load completions for every new session, execute once:
completionShells = map[string]func(out io.Writer, cmd *cobra.Command) error{ $ helm completion zsh > "${fpath[1]}/_helm"
"bash": runCompletionBash, `
"zsh": runCompletionZsh,
}
)
func newCompletionCmd(out io.Writer) *cobra.Command { func newCompletionCmd(out io.Writer) *cobra.Command {
shells := []string{}
for s := range completionShells {
shells = append(shells, s)
}
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "completion SHELL", Use: "completion",
Short: "generate autocompletions script for the specified shell (bash or zsh)", Short: "generate autocompletions script for the specified shell",
Long: completionDesc, Long: completionDesc,
Args: require.NoArgs,
}
bash := &cobra.Command{
Use: "bash",
Short: "generate autocompletions script for bash",
Long: bashCompDesc,
Args: require.NoArgs,
DisableFlagsInUseLine: true,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return runCompletion(out, cmd, args) return runCompletionBash(out, cmd)
}, },
ValidArgs: shells,
} }
return cmd zsh := &cobra.Command{
} Use: "zsh",
Short: "generate autocompletions script for zsh",
func runCompletion(out io.Writer, cmd *cobra.Command, args []string) error { Long: zshCompDesc,
if len(args) == 0 { Args: require.NoArgs,
return errors.New("shell not specified") DisableFlagsInUseLine: true,
} RunE: func(cmd *cobra.Command, args []string) error {
if len(args) > 1 { return runCompletionZsh(out, cmd)
return errors.New("too many arguments, expected only the shell type") },
}
run, found := completionShells[args[0]]
if !found {
return errors.Errorf("unsupported shell type %q", args[0])
} }
return run(out, cmd) cmd.AddCommand(bash, zsh)
return cmd
} }
func runCompletionBash(out io.Writer, cmd *cobra.Command) error { func runCompletionBash(out io.Writer, cmd *cobra.Command) error {

@ -48,7 +48,7 @@ func newDocsCmd(out io.Writer) *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "docs", Use: "docs",
Short: "Generate documentation as markdown or man pages", Short: "generate documentation as markdown or man pages",
Long: docsDesc, Long: docsDesc,
Hidden: true, Hidden: true,
Args: require.NoArgs, Args: require.NoArgs,

@ -21,53 +21,35 @@ import (
"io" "io"
"sort" "sort"
"helm.sh/helm/v3/pkg/cli"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"helm.sh/helm/v3/cmd/helm/require" "helm.sh/helm/v3/cmd/helm/require"
) )
var ( var envHelp = `
envHelp = `
Env prints out all the environment information in use by Helm. Env prints out all the environment information in use by Helm.
` `
)
func newEnvCmd(out io.Writer) *cobra.Command { func newEnvCmd(out io.Writer) *cobra.Command {
o := &envOptions{}
o.settings = cli.New()
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "env", Use: "env",
Short: "helm client environment information", Short: "helm client environment information",
Long: envHelp, Long: envHelp,
Args: require.NoArgs, Args: require.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error { Run: func(cmd *cobra.Command, args []string) {
return o.run(out) envVars := settings.EnvVars()
// Sort the variables by alphabetical order.
// This allows for a constant output across calls to 'helm env'.
var keys []string
for k := range envVars {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Fprintf(out, "%s=\"%s\"\n", k, envVars[k])
}
}, },
} }
return cmd return cmd
} }
type envOptions struct {
settings *cli.EnvSettings
}
func (o *envOptions) run(out io.Writer) error {
envVars := o.settings.EnvVars()
// Sort the variables by alphabetical order.
// This allows for a constant output across calls to 'helm env'.
var keys []string
for k := range envVars {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Printf("%s=\"%s\"\n", k, envVars[k])
}
return nil
}

@ -18,16 +18,19 @@ package main
import ( import (
"fmt" "fmt"
"log"
"path/filepath"
"strings" "strings"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/pflag" "github.com/spf13/pflag"
"helm.sh/helm/v3/internal/completion"
"helm.sh/helm/v3/pkg/action" "helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/cli/output" "helm.sh/helm/v3/pkg/cli/output"
"helm.sh/helm/v3/pkg/cli/values" "helm.sh/helm/v3/pkg/cli/values"
"helm.sh/helm/v3/pkg/helmpath"
"helm.sh/helm/v3/pkg/postrender" "helm.sh/helm/v3/pkg/postrender"
"helm.sh/helm/v3/pkg/repo"
) )
const outputFlag = "output" const outputFlag = "output"
@ -41,33 +44,37 @@ func addValueOptionsFlags(f *pflag.FlagSet, v *values.Options) {
} }
func addChartPathOptionsFlags(f *pflag.FlagSet, c *action.ChartPathOptions) { func addChartPathOptionsFlags(f *pflag.FlagSet, c *action.ChartPathOptions) {
f.StringVar(&c.Version, "version", "", "specify the exact chart version to install. If this is not specified, the latest version is installed") f.StringVar(&c.Version, "version", "", "specify the exact chart version to use. If this is not specified, the latest version is used")
f.BoolVar(&c.Verify, "verify", false, "verify the package before installing it") f.BoolVar(&c.Verify, "verify", false, "verify the package before using it")
f.StringVar(&c.Keyring, "keyring", defaultKeyring(), "location of public keys used for verification") f.StringVar(&c.Keyring, "keyring", defaultKeyring(), "location of public keys used for verification")
f.StringVar(&c.RepoURL, "repo", "", "chart repository url where to locate the requested chart") f.StringVar(&c.RepoURL, "repo", "", "chart repository url where to locate the requested chart")
f.StringVar(&c.Username, "username", "", "chart repository username where to locate the requested chart") f.StringVar(&c.Username, "username", "", "chart repository username where to locate the requested chart")
f.StringVar(&c.Password, "password", "", "chart repository password where to locate the requested chart") f.StringVar(&c.Password, "password", "", "chart repository password where to locate the requested chart")
f.StringVar(&c.CertFile, "cert-file", "", "identify HTTPS client using this SSL certificate file") f.StringVar(&c.CertFile, "cert-file", "", "identify HTTPS client using this SSL certificate file")
f.StringVar(&c.KeyFile, "key-file", "", "identify HTTPS client using this SSL key file") f.StringVar(&c.KeyFile, "key-file", "", "identify HTTPS client using this SSL key file")
f.BoolVar(&c.InsecureSkipTLSverify, "insecure-skip-tls-verify", false, "skip tls certificate checks for the chart download")
f.StringVar(&c.CaFile, "ca-file", "", "verify certificates of HTTPS-enabled servers using this CA bundle") f.StringVar(&c.CaFile, "ca-file", "", "verify certificates of HTTPS-enabled servers using this CA bundle")
} }
// bindOutputFlag will add the output flag to the given command and bind the // bindOutputFlag will add the output flag to the given command and bind the
// value to the given format pointer // value to the given format pointer
func bindOutputFlag(cmd *cobra.Command, varRef *output.Format) { func bindOutputFlag(cmd *cobra.Command, varRef *output.Format) {
f := cmd.Flags() cmd.Flags().VarP(newOutputValue(output.Table, varRef), outputFlag, "o",
flag := f.VarPF(newOutputValue(output.Table, varRef), outputFlag, "o",
fmt.Sprintf("prints the output in the specified format. Allowed values: %s", strings.Join(output.Formats(), ", "))) fmt.Sprintf("prints the output in the specified format. Allowed values: %s", strings.Join(output.Formats(), ", ")))
completion.RegisterFlagCompletionFunc(flag, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) { err := cmd.RegisterFlagCompletionFunc(outputFlag, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
var formatNames []string var formatNames []string
for _, format := range output.Formats() { for _, format := range output.Formats() {
if strings.HasPrefix(format, toComplete) { if strings.HasPrefix(format, toComplete) {
formatNames = append(formatNames, format) formatNames = append(formatNames, format)
} }
} }
return formatNames, completion.BashCompDirectiveDefault return formatNames, cobra.ShellCompDirectiveDefault
}) })
if err != nil {
log.Fatal(err)
}
} }
type outputValue output.Format type outputValue output.Format
@ -124,3 +131,27 @@ func (p postRenderer) Set(s string) error {
*p.renderer = pr *p.renderer = pr
return nil return nil
} }
func compVersionFlag(chartRef string, toComplete string) ([]string, cobra.ShellCompDirective) {
chartInfo := strings.Split(chartRef, "/")
if len(chartInfo) != 2 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
repoName := chartInfo[0]
chartName := chartInfo[1]
path := filepath.Join(settings.RepositoryCache, helmpath.CacheIndexFile(repoName))
var versions []string
if indexFile, err := repo.LoadIndexFile(path); err == nil {
for _, details := range indexFile.Entries[chartName] {
version := details.Metadata.Version
if strings.HasPrefix(version, toComplete) {
versions = append(versions, version)
}
}
}
return versions, cobra.ShellCompDirectiveNoFileComp
}

@ -18,11 +18,11 @@ package main
import ( import (
"io" "io"
"log"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"helm.sh/helm/v3/cmd/helm/require" "helm.sh/helm/v3/cmd/helm/require"
"helm.sh/helm/v3/internal/completion"
"helm.sh/helm/v3/pkg/action" "helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/cli/output" "helm.sh/helm/v3/pkg/cli/output"
) )
@ -41,6 +41,12 @@ func newGetAllCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
Short: "download all information for a named release", Short: "download all information for a named release",
Long: getAllHelp, Long: getAllHelp,
Args: require.ExactArgs(1), Args: require.ExactArgs(1),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return compListReleases(toComplete, cfg)
},
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
res, err := client.Run(args[0]) res, err := client.Run(args[0])
if err != nil { if err != nil {
@ -57,24 +63,19 @@ func newGetAllCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
}, },
} }
// Function providing dynamic auto-completion
completion.RegisterValidArgsFunc(cmd, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) {
if len(args) != 0 {
return nil, completion.BashCompDirectiveNoFileComp
}
return compListReleases(toComplete, cfg)
})
f := cmd.Flags() f := cmd.Flags()
f.IntVar(&client.Version, "revision", 0, "get the named release with revision") f.IntVar(&client.Version, "revision", 0, "get the named release with revision")
flag := f.Lookup("revision") err := cmd.RegisterFlagCompletionFunc("revision", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
completion.RegisterFlagCompletionFunc(flag, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) {
if len(args) == 1 { if len(args) == 1 {
return compListRevisions(cfg, args[0]) return compListRevisions(toComplete, cfg, args[0])
} }
return nil, completion.BashCompDirectiveNoFileComp return nil, cobra.ShellCompDirectiveNoFileComp
}) })
if err != nil {
log.Fatal(err)
}
f.StringVar(&template, "template", "", "go template for formatting the output, eg: {{.Release.Name}}") f.StringVar(&template, "template", "", "go template for formatting the output, eg: {{.Release.Name}}")
return cmd return cmd

@ -19,11 +19,11 @@ package main
import ( import (
"fmt" "fmt"
"io" "io"
"log"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"helm.sh/helm/v3/cmd/helm/require" "helm.sh/helm/v3/cmd/helm/require"
"helm.sh/helm/v3/internal/completion"
"helm.sh/helm/v3/pkg/action" "helm.sh/helm/v3/pkg/action"
) )
@ -41,6 +41,12 @@ func newGetHooksCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
Short: "download all hooks for a named release", Short: "download all hooks for a named release",
Long: getHooksHelp, Long: getHooksHelp,
Args: require.ExactArgs(1), Args: require.ExactArgs(1),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return compListReleases(toComplete, cfg)
},
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
res, err := client.Run(args[0]) res, err := client.Run(args[0])
if err != nil { if err != nil {
@ -53,23 +59,17 @@ func newGetHooksCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
}, },
} }
// Function providing dynamic auto-completion cmd.Flags().IntVar(&client.Version, "revision", 0, "get the named release with revision")
completion.RegisterValidArgsFunc(cmd, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) { err := cmd.RegisterFlagCompletionFunc("revision", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, completion.BashCompDirectiveNoFileComp
}
return compListReleases(toComplete, cfg)
})
f := cmd.Flags()
f.IntVar(&client.Version, "revision", 0, "get the named release with revision")
flag := f.Lookup("revision")
completion.RegisterFlagCompletionFunc(flag, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) {
if len(args) == 1 { if len(args) == 1 {
return compListRevisions(cfg, args[0]) return compListRevisions(toComplete, cfg, args[0])
} }
return nil, completion.BashCompDirectiveNoFileComp return nil, cobra.ShellCompDirectiveNoFileComp
}) })
if err != nil {
log.Fatal(err)
}
return cmd return cmd
} }

@ -19,11 +19,11 @@ package main
import ( import (
"fmt" "fmt"
"io" "io"
"log"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"helm.sh/helm/v3/cmd/helm/require" "helm.sh/helm/v3/cmd/helm/require"
"helm.sh/helm/v3/internal/completion"
"helm.sh/helm/v3/pkg/action" "helm.sh/helm/v3/pkg/action"
) )
@ -43,6 +43,12 @@ func newGetManifestCmd(cfg *action.Configuration, out io.Writer) *cobra.Command
Short: "download the manifest for a named release", Short: "download the manifest for a named release",
Long: getManifestHelp, Long: getManifestHelp,
Args: require.ExactArgs(1), Args: require.ExactArgs(1),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return compListReleases(toComplete, cfg)
},
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
res, err := client.Run(args[0]) res, err := client.Run(args[0])
if err != nil { if err != nil {
@ -53,23 +59,17 @@ func newGetManifestCmd(cfg *action.Configuration, out io.Writer) *cobra.Command
}, },
} }
// Function providing dynamic auto-completion cmd.Flags().IntVar(&client.Version, "revision", 0, "get the named release with revision")
completion.RegisterValidArgsFunc(cmd, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) { err := cmd.RegisterFlagCompletionFunc("revision", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, completion.BashCompDirectiveNoFileComp
}
return compListReleases(toComplete, cfg)
})
f := cmd.Flags()
f.IntVar(&client.Version, "revision", 0, "get the named release with revision")
flag := f.Lookup("revision")
completion.RegisterFlagCompletionFunc(flag, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) {
if len(args) == 1 { if len(args) == 1 {
return compListRevisions(cfg, args[0]) return compListRevisions(toComplete, cfg, args[0])
} }
return nil, completion.BashCompDirectiveNoFileComp return nil, cobra.ShellCompDirectiveNoFileComp
}) })
if err != nil {
log.Fatal(err)
}
return cmd return cmd
} }

@ -19,11 +19,11 @@ package main
import ( import (
"fmt" "fmt"
"io" "io"
"log"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"helm.sh/helm/v3/cmd/helm/require" "helm.sh/helm/v3/cmd/helm/require"
"helm.sh/helm/v3/internal/completion"
"helm.sh/helm/v3/pkg/action" "helm.sh/helm/v3/pkg/action"
) )
@ -39,6 +39,12 @@ func newGetNotesCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
Short: "download the notes for a named release", Short: "download the notes for a named release",
Long: getNotesHelp, Long: getNotesHelp,
Args: require.ExactArgs(1), Args: require.ExactArgs(1),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return compListReleases(toComplete, cfg)
},
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
res, err := client.Run(args[0]) res, err := client.Run(args[0])
if err != nil { if err != nil {
@ -51,23 +57,18 @@ func newGetNotesCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
}, },
} }
// Function providing dynamic auto-completion
completion.RegisterValidArgsFunc(cmd, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) {
if len(args) != 0 {
return nil, completion.BashCompDirectiveNoFileComp
}
return compListReleases(toComplete, cfg)
})
f := cmd.Flags() f := cmd.Flags()
f.IntVar(&client.Version, "revision", 0, "get the named release with revision") f.IntVar(&client.Version, "revision", 0, "get the named release with revision")
flag := f.Lookup("revision") err := cmd.RegisterFlagCompletionFunc("revision", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
completion.RegisterFlagCompletionFunc(flag, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) {
if len(args) == 1 { if len(args) == 1 {
return compListRevisions(cfg, args[0]) return compListRevisions(toComplete, cfg, args[0])
} }
return nil, completion.BashCompDirectiveNoFileComp return nil, cobra.ShellCompDirectiveNoFileComp
}) })
if err != nil {
log.Fatal(err)
}
return cmd return cmd
} }

@ -19,11 +19,11 @@ package main
import ( import (
"fmt" "fmt"
"io" "io"
"log"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"helm.sh/helm/v3/cmd/helm/require" "helm.sh/helm/v3/cmd/helm/require"
"helm.sh/helm/v3/internal/completion"
"helm.sh/helm/v3/pkg/action" "helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/cli/output" "helm.sh/helm/v3/pkg/cli/output"
) )
@ -46,6 +46,12 @@ func newGetValuesCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
Short: "download the values file for a named release", Short: "download the values file for a named release",
Long: getValuesHelp, Long: getValuesHelp,
Args: require.ExactArgs(1), Args: require.ExactArgs(1),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return compListReleases(toComplete, cfg)
},
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
vals, err := client.Run(args[0]) vals, err := client.Run(args[0])
if err != nil { if err != nil {
@ -55,23 +61,19 @@ func newGetValuesCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
}, },
} }
// Function providing dynamic auto-completion
completion.RegisterValidArgsFunc(cmd, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) {
if len(args) != 0 {
return nil, completion.BashCompDirectiveNoFileComp
}
return compListReleases(toComplete, cfg)
})
f := cmd.Flags() f := cmd.Flags()
f.IntVar(&client.Version, "revision", 0, "get the named release with revision") f.IntVar(&client.Version, "revision", 0, "get the named release with revision")
flag := f.Lookup("revision") err := cmd.RegisterFlagCompletionFunc("revision", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
completion.RegisterFlagCompletionFunc(flag, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) {
if len(args) == 1 { if len(args) == 1 {
return compListRevisions(cfg, args[0]) return compListRevisions(toComplete, cfg, args[0])
} }
return nil, completion.BashCompDirectiveNoFileComp return nil, cobra.ShellCompDirectiveNoFileComp
}) })
if err != nil {
log.Fatal(err)
}
f.BoolVarP(&client.AllValues, "all", "a", false, "dump all (computed) values") f.BoolVarP(&client.AllValues, "all", "a", false, "dump all (computed) values")
bindOutputFlag(cmd, &outfmt) bindOutputFlag(cmd, &outfmt)

@ -43,9 +43,7 @@ import (
// FeatureGateOCI is the feature gate for checking if `helm chart` and `helm registry` commands should work // FeatureGateOCI is the feature gate for checking if `helm chart` and `helm registry` commands should work
const FeatureGateOCI = gates.Gate("HELM_EXPERIMENTAL_OCI") const FeatureGateOCI = gates.Gate("HELM_EXPERIMENTAL_OCI")
var ( var settings = cli.New()
settings = cli.New()
)
func init() { func init() {
log.SetFlags(log.Lshortfile) log.SetFlags(log.Lshortfile)
@ -58,6 +56,11 @@ func debug(format string, v ...interface{}) {
} }
} }
func warning(format string, v ...interface{}) {
format = fmt.Sprintf("WARNING: %s\n", format)
fmt.Fprintf(os.Stderr, format, v...)
}
func initKubeLogs() { func initKubeLogs() {
pflag.CommandLine.SetNormalizeFunc(wordSepNormalizeFunc) pflag.CommandLine.SetNormalizeFunc(wordSepNormalizeFunc)
gofs := flag.NewFlagSet("klog", flag.ExitOnError) gofs := flag.NewFlagSet("klog", flag.ExitOnError)
@ -70,16 +73,23 @@ func main() {
initKubeLogs() initKubeLogs()
actionConfig := new(action.Configuration) actionConfig := new(action.Configuration)
cmd := newRootCmd(actionConfig, os.Stdout, os.Args[1:]) cmd, err := newRootCmd(actionConfig, os.Stdout, os.Args[1:])
if err != nil {
helmDriver := os.Getenv("HELM_DRIVER") debug("%+v", err)
if err := actionConfig.Init(settings.RESTClientGetter(), settings.Namespace(), helmDriver, debug); err != nil { os.Exit(1)
log.Fatal(err)
}
if helmDriver == "memory" {
loadReleasesInMemory(actionConfig)
} }
// run when each command's execute method is called
cobra.OnInitialize(func() {
helmDriver := os.Getenv("HELM_DRIVER")
if err := actionConfig.Init(settings.RESTClientGetter(), settings.Namespace(), helmDriver, debug); err != nil {
log.Fatal(err)
}
if helmDriver == "memory" {
loadReleasesInMemory(actionConfig)
}
})
if err := cmd.Execute(); err != nil { if err := cmd.Execute(); err != nil {
debug("%+v", err) debug("%+v", err)
switch e := err.(type) { switch e := err.(type) {

@ -115,7 +115,11 @@ func executeActionCommandStdinC(store *storage.Storage, in *os.File, cmd string)
Log: func(format string, v ...interface{}) {}, Log: func(format string, v ...interface{}) {},
} }
root := newRootCmd(actionConfig, buf, args) root, err := newRootCmd(actionConfig, buf, args)
if err != nil {
return nil, "", err
}
root.SetOut(buf) root.SetOut(buf)
root.SetErr(buf) root.SetErr(buf)
root.SetArgs(args) root.SetArgs(args)

@ -20,13 +20,13 @@ import (
"fmt" "fmt"
"io" "io"
"strconv" "strconv"
"strings"
"time" "time"
"github.com/gosuri/uitable" "github.com/gosuri/uitable"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"helm.sh/helm/v3/cmd/helm/require" "helm.sh/helm/v3/cmd/helm/require"
"helm.sh/helm/v3/internal/completion"
"helm.sh/helm/v3/pkg/action" "helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/chart" "helm.sh/helm/v3/pkg/chart"
"helm.sh/helm/v3/pkg/cli/output" "helm.sh/helm/v3/pkg/cli/output"
@ -61,6 +61,12 @@ func newHistoryCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
Short: "fetch release history", Short: "fetch release history",
Aliases: []string{"hist"}, Aliases: []string{"hist"},
Args: require.ExactArgs(1), Args: require.ExactArgs(1),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return compListReleases(toComplete, cfg)
},
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
history, err := getHistory(client, args[0]) history, err := getHistory(client, args[0])
if err != nil { if err != nil {
@ -71,14 +77,6 @@ func newHistoryCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
}, },
} }
// Function providing dynamic auto-completion
completion.RegisterValidArgsFunc(cmd, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) {
if len(args) != 0 {
return nil, completion.BashCompDirectiveNoFileComp
}
return compListReleases(toComplete, cfg)
})
f := cmd.Flags() f := cmd.Flags()
f.IntVar(&client.Max, "max", 256, "maximum number of revision to include in history") f.IntVar(&client.Max, "max", 256, "maximum number of revision to include in history")
bindOutputFlag(cmd, &outfmt) bindOutputFlag(cmd, &outfmt)
@ -187,15 +185,18 @@ func min(x, y int) int {
return y return y
} }
func compListRevisions(cfg *action.Configuration, releaseName string) ([]string, completion.BashCompDirective) { func compListRevisions(toComplete string, cfg *action.Configuration, releaseName string) ([]string, cobra.ShellCompDirective) {
client := action.NewHistory(cfg) client := action.NewHistory(cfg)
var revisions []string var revisions []string
if hist, err := client.Run(releaseName); err == nil { if hist, err := client.Run(releaseName); err == nil {
for _, release := range hist { for _, release := range hist {
revisions = append(revisions, strconv.Itoa(release.Version)) version := strconv.Itoa(release.Version)
if strings.HasPrefix(version, toComplete) {
revisions = append(revisions, version)
}
} }
return revisions, completion.BashCompDirectiveDefault return revisions, cobra.ShellCompDirectiveNoFileComp
} }
return nil, completion.BashCompDirectiveError return nil, cobra.ShellCompDirectiveError
} }

@ -17,8 +17,8 @@ limitations under the License.
package main package main
import ( import (
"fmt"
"io" "io"
"log"
"time" "time"
"github.com/pkg/errors" "github.com/pkg/errors"
@ -26,7 +26,6 @@ import (
"github.com/spf13/pflag" "github.com/spf13/pflag"
"helm.sh/helm/v3/cmd/helm/require" "helm.sh/helm/v3/cmd/helm/require"
"helm.sh/helm/v3/internal/completion"
"helm.sh/helm/v3/pkg/action" "helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/chart" "helm.sh/helm/v3/pkg/chart"
"helm.sh/helm/v3/pkg/chart/loader" "helm.sh/helm/v3/pkg/chart/loader"
@ -60,6 +59,7 @@ or
$ helm install --set-string long_int=1234567890 myredis ./redis $ helm install --set-string long_int=1234567890 myredis ./redis
or or
$ helm install --set-file my_script=dothings.sh myredis ./redis $ helm install --set-file my_script=dothings.sh myredis ./redis
You can specify the '--values'/'-f' flag multiple times. The priority will be given to the You can specify the '--values'/'-f' flag multiple times. The priority will be given to the
@ -113,6 +113,9 @@ func newInstallCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
Short: "install a chart", Short: "install a chart",
Long: installDesc, Long: installDesc,
Args: require.MinimumNArgs(1), Args: require.MinimumNArgs(1),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return compInstall(args, toComplete, client)
},
RunE: func(_ *cobra.Command, args []string) error { RunE: func(_ *cobra.Command, args []string) error {
rel, err := runInstall(args, client, valueOpts, out) rel, err := runInstall(args, client, valueOpts, out)
if err != nil { if err != nil {
@ -123,19 +126,14 @@ func newInstallCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
}, },
} }
// Function providing dynamic auto-completion addInstallFlags(cmd, cmd.Flags(), client, valueOpts)
completion.RegisterValidArgsFunc(cmd, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) {
return compInstall(args, toComplete, client)
})
addInstallFlags(cmd.Flags(), client, valueOpts)
bindOutputFlag(cmd, &outfmt) bindOutputFlag(cmd, &outfmt)
bindPostRenderFlag(cmd, &client.PostRenderer) bindPostRenderFlag(cmd, &client.PostRenderer)
return cmd return cmd
} }
func addInstallFlags(f *pflag.FlagSet, client *action.Install, valueOpts *values.Options) { func addInstallFlags(cmd *cobra.Command, f *pflag.FlagSet, client *action.Install, valueOpts *values.Options) {
f.BoolVar(&client.CreateNamespace, "create-namespace", false, "create the release namespace if not present") f.BoolVar(&client.CreateNamespace, "create-namespace", false, "create the release namespace if not present")
f.BoolVar(&client.DryRun, "dry-run", false, "simulate an install") f.BoolVar(&client.DryRun, "dry-run", false, "simulate an install")
f.BoolVar(&client.DisableHooks, "no-hooks", false, "prevent hooks from running during install") f.BoolVar(&client.DisableHooks, "no-hooks", false, "prevent hooks from running during install")
@ -153,6 +151,21 @@ func addInstallFlags(f *pflag.FlagSet, client *action.Install, valueOpts *values
f.BoolVar(&client.SubNotes, "render-subchart-notes", false, "if set, render subchart notes along with the parent") f.BoolVar(&client.SubNotes, "render-subchart-notes", false, "if set, render subchart notes along with the parent")
addValueOptionsFlags(f, valueOpts) addValueOptionsFlags(f, valueOpts)
addChartPathOptionsFlags(f, &client.ChartPathOptions) addChartPathOptionsFlags(f, &client.ChartPathOptions)
err := cmd.RegisterFlagCompletionFunc("version", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
requiredArgs := 2
if client.GenerateName {
requiredArgs = 1
}
if len(args) != requiredArgs {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return compVersionFlag(args[requiredArgs-1], toComplete)
})
if err != nil {
log.Fatal(err)
}
} }
func runInstall(args []string, client *action.Install, valueOpts *values.Options, out io.Writer) (*release.Release, error) { func runInstall(args []string, client *action.Install, valueOpts *values.Options, out io.Writer) (*release.Release, error) {
@ -193,7 +206,7 @@ func runInstall(args []string, client *action.Install, valueOpts *values.Options
} }
if chartRequested.Metadata.Deprecated { if chartRequested.Metadata.Deprecated {
fmt.Fprintln(out, "WARNING: This chart is deprecated") warning("This chart is deprecated")
} }
if req := chartRequested.Metadata.Dependencies; req != nil { if req := chartRequested.Metadata.Dependencies; req != nil {
@ -241,7 +254,7 @@ func isChartInstallable(ch *chart.Chart) (bool, error) {
} }
// Provide dynamic auto-completion for the install and template commands // Provide dynamic auto-completion for the install and template commands
func compInstall(args []string, toComplete string, client *action.Install) ([]string, completion.BashCompDirective) { func compInstall(args []string, toComplete string, client *action.Install) ([]string, cobra.ShellCompDirective) {
requiredArgs := 1 requiredArgs := 1
if client.GenerateName { if client.GenerateName {
requiredArgs = 0 requiredArgs = 0
@ -249,5 +262,5 @@ func compInstall(args []string, toComplete string, client *action.Install) ([]st
if len(args) == requiredArgs { if len(args) == requiredArgs {
return compListCharts(toComplete, true) return compListCharts(toComplete, true)
} }
return nil, completion.BashCompDirectiveNoFileComp return nil, cobra.ShellCompDirectiveNoFileComp
} }

@ -17,6 +17,7 @@ limitations under the License.
package main package main
import ( import (
"fmt"
"testing" "testing"
) )
@ -195,6 +196,11 @@ func TestInstall(t *testing.T) {
cmd: "install aeneas testdata/testcharts/deprecated --namespace default", cmd: "install aeneas testdata/testcharts/deprecated --namespace default",
golden: "output/deprecated-chart.txt", 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",
},
} }
runTestActionCmd(t, tests) runTestActionCmd(t, tests)
@ -203,3 +209,33 @@ func TestInstall(t *testing.T) {
func TestInstallOutputCompletion(t *testing.T) { func TestInstallOutputCompletion(t *testing.T) {
outputFlagCompletionTest(t, "install") 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 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)
}

@ -46,7 +46,7 @@ func newLintCmd(out io.Writer) *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "lint PATH", Use: "lint PATH",
Short: "examines a chart for possible issues", Short: "examine a chart for possible issues",
Long: longLintHelp, Long: longLintHelp,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
paths := []string{"."} paths := []string{"."}

@ -26,7 +26,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"helm.sh/helm/v3/cmd/helm/require" "helm.sh/helm/v3/cmd/helm/require"
"helm.sh/helm/v3/internal/completion"
"helm.sh/helm/v3/pkg/action" "helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/cli/output" "helm.sh/helm/v3/pkg/cli/output"
"helm.sh/helm/v3/pkg/release" "helm.sh/helm/v3/pkg/release"
@ -186,8 +185,8 @@ func (r *releaseListWriter) WriteYAML(out io.Writer) error {
} }
// Provide dynamic auto-completion for release names // Provide dynamic auto-completion for release names
func compListReleases(toComplete string, cfg *action.Configuration) ([]string, completion.BashCompDirective) { func compListReleases(toComplete string, cfg *action.Configuration) ([]string, cobra.ShellCompDirective) {
completion.CompDebugln(fmt.Sprintf("compListReleases with toComplete %s", toComplete)) cobra.CompDebugln(fmt.Sprintf("compListReleases with toComplete %s", toComplete), settings.Debug)
client := action.NewList(cfg) client := action.NewList(cfg)
client.All = true client.All = true
@ -197,7 +196,7 @@ func compListReleases(toComplete string, cfg *action.Configuration) ([]string, c
client.SetStateMask() client.SetStateMask()
results, err := client.Run() results, err := client.Run()
if err != nil { if err != nil {
return nil, completion.BashCompDirectiveDefault return nil, cobra.ShellCompDirectiveDefault
} }
var choices []string var choices []string
@ -205,5 +204,5 @@ func compListReleases(toComplete string, cfg *action.Configuration) ([]string, c
choices = append(choices, res.Name) choices = append(choices, res.Name)
} }
return choices, completion.BashCompDirectiveNoFileComp return choices, cobra.ShellCompDirectiveNoFileComp
} }

@ -32,7 +32,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"sigs.k8s.io/yaml" "sigs.k8s.io/yaml"
"helm.sh/helm/v3/internal/completion"
"helm.sh/helm/v3/pkg/plugin" "helm.sh/helm/v3/pkg/plugin"
) )
@ -64,21 +63,6 @@ func loadPlugins(baseCmd *cobra.Command, out io.Writer) {
return return
} }
processParent := func(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
}
// If we are dealing with the completion command, we try to load more details about the plugins
// if available, so as to allow for command and flag completion
if subCmd, _, err := baseCmd.Find(os.Args[1:]); err == nil && subCmd.Name() == "completion" {
loadPluginsForCompletion(baseCmd, found)
return
}
// Now we create commands for all of these. // Now we create commands for all of these.
for _, plug := range found { for _, plug := range found {
plug := plug plug := plug
@ -87,33 +71,6 @@ func loadPlugins(baseCmd *cobra.Command, out io.Writer) {
md.Usage = fmt.Sprintf("the %q plugin", md.Name) md.Usage = fmt.Sprintf("the %q plugin", md.Name)
} }
// This function is used to setup the environment for the plugin and then
// call the executable specified by the parameter 'main'
callPluginExecutable := func(cmd *cobra.Command, main string, argv []string, out io.Writer) error {
env := os.Environ()
for k, v := range settings.EnvVars() {
env = append(env, fmt.Sprintf("%s=%s", k, v))
}
prog := exec.Command(main, argv...)
prog.Env = env
prog.Stdin = os.Stdin
prog.Stdout = out
prog.Stderr = os.Stderr
if err := prog.Run(); err != nil {
if eerr, ok := err.(*exec.ExitError); ok {
os.Stderr.Write(eerr.Stderr)
status := eerr.Sys().(syscall.WaitStatus)
return pluginError{
error: errors.Errorf("plugin %q exited with error", md.Name),
code: status.ExitStatus(),
}
}
return err
}
return nil
}
c := &cobra.Command{ c := &cobra.Command{
Use: md.Name, Use: md.Name,
Short: md.Usage, Short: md.Usage,
@ -134,62 +91,61 @@ func loadPlugins(baseCmd *cobra.Command, out io.Writer) {
return errors.Errorf("plugin %q exited with error", md.Name) return errors.Errorf("plugin %q exited with error", md.Name)
} }
return callPluginExecutable(cmd, main, argv, out) return callPluginExecutable(md.Name, main, argv, out)
}, },
// This passes all the flags to the subcommand. // This passes all the flags to the subcommand.
DisableFlagParsing: true, DisableFlagParsing: true,
} }
// Setup dynamic completion for the plugin // TODO: Make sure a command with this name does not already exist.
completion.RegisterValidArgsFunc(c, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) { baseCmd.AddCommand(c)
u, err := processParent(cmd, args)
if err != nil {
return nil, completion.BashCompDirectiveError
}
// We will call the dynamic completion script of the plugin
main := strings.Join([]string{plug.Dir, pluginDynamicCompletionExecutable}, string(filepath.Separator))
argv := []string{} // For completion, we try to load more details about the plugins so as to allow for command and
if !md.IgnoreFlags { // flag completion of the plugin itself.
argv = append(argv, u...) // We only do this when necessary (for the "completion" and "__complete" commands) to avoid the
argv = append(argv, toComplete) // risk of a rogue plugin affecting Helm's normal behavior.
} subCmd, _, err := baseCmd.Find(os.Args[1:])
plugin.SetupPluginEnv(settings, md.Name, plug.Dir) if (err == nil &&
((subCmd.HasParent() && subCmd.Parent().Name() == "completion") || subCmd.Name() == cobra.ShellCompRequestCmd)) ||
/* for the tests */ subCmd == baseCmd.Root() {
loadCompletionForPlugin(c, plug)
}
}
}
completion.CompDebugln(fmt.Sprintf("calling %s with args %v", main, argv)) func processParent(cmd *cobra.Command, args []string) ([]string, error) {
buf := new(bytes.Buffer) k, u := manuallyProcessArgs(args)
if err := callPluginExecutable(cmd, main, argv, buf); err != nil { if err := cmd.Parent().ParseFlags(k); err != nil {
return nil, completion.BashCompDirectiveError return nil, err
} }
return u, nil
}
var completions []string // This function is used to setup the environment for the plugin and then
for _, comp := range strings.Split(buf.String(), "\n") { // call the executable specified by the parameter 'main'
// Remove any empty lines func callPluginExecutable(pluginName string, main string, argv []string, out io.Writer) error {
if len(comp) > 0 { env := os.Environ()
completions = append(completions, comp) for k, v := range settings.EnvVars() {
} env = append(env, fmt.Sprintf("%s=%s", k, v))
} }
// Check if the last line of output is of the form :<integer>, which prog := exec.Command(main, argv...)
// indicates the BashCompletionDirective. prog.Env = env
directive := completion.BashCompDirectiveDefault prog.Stdin = os.Stdin
if len(completions) > 0 { prog.Stdout = out
lastLine := completions[len(completions)-1] prog.Stderr = os.Stderr
if len(lastLine) > 1 && lastLine[0] == ':' { if err := prog.Run(); err != nil {
if strInt, err := strconv.Atoi(lastLine[1:]); err == nil { if eerr, ok := err.(*exec.ExitError); ok {
directive = completion.BashCompDirective(strInt) os.Stderr.Write(eerr.Stderr)
completions = completions[:len(completions)-1] status := eerr.Sys().(syscall.WaitStatus)
} return pluginError{
} error: errors.Errorf("plugin %q exited with error", pluginName),
code: status.ExitStatus(),
} }
}
return completions, directive return err
})
// TODO: Make sure a command with this name does not already exist.
baseCmd.AddCommand(c)
} }
return nil
} }
// manuallyProcessArgs processes an arg array, removing special args. // manuallyProcessArgs processes an arg array, removing special args.
@ -246,35 +202,31 @@ type pluginCommand struct {
Commands []pluginCommand `json:"commands"` Commands []pluginCommand `json:"commands"`
} }
// loadPluginsForCompletion will load and parse any completion.yaml provided by the plugins // loadCompletionForPlugin will load and parse any completion.yaml provided by the plugin
func loadPluginsForCompletion(baseCmd *cobra.Command, plugins []*plugin.Plugin) { // and add the dynamic completion hook to call the optional plugin.complete
for _, plug := range plugins { func loadCompletionForPlugin(pluginCmd *cobra.Command, plugin *plugin.Plugin) {
// Parse the yaml file providing the plugin's subcmds and flags // Parse the yaml file providing the plugin's sub-commands and flags
cmds, err := loadFile(strings.Join( cmds, err := loadFile(strings.Join(
[]string{plug.Dir, pluginStaticCompletionFile}, string(filepath.Separator))) []string{plugin.Dir, pluginStaticCompletionFile}, string(filepath.Separator)))
if err != nil { if err != nil {
// The file could be missing or invalid. Either way, we at least create the command // The file could be missing or invalid. No static completion for this plugin.
// for the plugin name. if settings.Debug {
if settings.Debug { log.Output(2, fmt.Sprintf("[info] %s\n", err.Error()))
log.Output(2, fmt.Sprintf("[info] %s\n", err.Error()))
}
cmds = &pluginCommand{Name: plug.Metadata.Name}
} }
// Continue to setup dynamic completion.
cmds = &pluginCommand{}
}
// We know what the plugin name must be. // Preserve the Usage string specified for the plugin
// Let's set it in case the Name field was not specified correctly in the file. cmds.Name = pluginCmd.Use
// This insures that we will at least get the plugin name to complete, even if
// there is a problem with the completion.yaml file
cmds.Name = plug.Metadata.Name
addPluginCommands(baseCmd, cmds) addPluginCommands(plugin, pluginCmd, cmds)
}
} }
// addPluginCommands is a recursive method that adds the different levels // addPluginCommands is a recursive method that adds each different level
// of sub-commands and flags for the plugins that provide such information // of sub-commands and flags for the plugins that have provided such information
func addPluginCommands(baseCmd *cobra.Command, cmds *pluginCommand) { func addPluginCommands(plugin *plugin.Plugin, baseCmd *cobra.Command, cmds *pluginCommand) {
if cmds == nil { if cmds == nil {
return return
} }
@ -287,14 +239,19 @@ func addPluginCommands(baseCmd *cobra.Command, cmds *pluginCommand) {
return return
} }
// Create a fake command just so the completion script will include it baseCmd.Use = cmds.Name
c := &cobra.Command{ baseCmd.ValidArgs = cmds.ValidArgs
Use: cmds.Name, // Setup the same dynamic completion for each plugin sub-command.
ValidArgs: cmds.ValidArgs, // This is because if dynamic completion is triggered, there is a single executable
// A Run is required for it to be a valid command without subcommands // to call (plugin.complete), so every sub-commands calls it in the same fashion.
Run: func(cmd *cobra.Command, args []string) {}, 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(plugin, cmd, args, toComplete)
}
} }
baseCmd.AddCommand(c)
// Create fake flags. // Create fake flags.
if len(cmds.Flags) > 0 { if len(cmds.Flags) > 0 {
@ -314,7 +271,7 @@ func addPluginCommands(baseCmd *cobra.Command, cmds *pluginCommand) {
} }
} }
f := c.Flags() f := baseCmd.Flags()
if len(longs) >= len(shorts) { if len(longs) >= len(shorts) {
for i := range longs { for i := range longs {
if i < len(shorts) { if i < len(shorts) {
@ -338,7 +295,16 @@ func addPluginCommands(baseCmd *cobra.Command, cmds *pluginCommand) {
// Recursively add any sub-commands // Recursively add any sub-commands
for _, cmd := range cmds.Commands { for _, cmd := range cmds.Commands {
addPluginCommands(c, &cmd) // 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(cmd *cobra.Command, args []string) {},
}
baseCmd.AddCommand(subCmd)
addPluginCommands(plugin, subCmd, &cmd)
} }
} }
@ -353,3 +319,59 @@ func loadFile(path string) (*pluginCommand, error) {
err = yaml.Unmarshal(b, cmds) err = yaml.Unmarshal(b, cmds)
return cmds, err 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) {
md := plug.Metadata
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 !md.IgnoreFlags {
argv = append(argv, u...)
argv = append(argv, toComplete)
}
plugin.SetupPluginEnv(settings, md.Name, plug.Dir)
cobra.CompDebugln(fmt.Sprintf("calling %s with args %v", main, argv), settings.Debug)
buf := new(bytes.Buffer)
if err := callPluginExecutable(md.Name, main, argv, 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.Split(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
}

@ -24,7 +24,6 @@ import (
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"helm.sh/helm/v3/internal/completion"
"helm.sh/helm/v3/pkg/plugin" "helm.sh/helm/v3/pkg/plugin"
) )
@ -39,6 +38,12 @@ func newPluginUninstallCmd(out io.Writer) *cobra.Command {
Use: "uninstall <plugin>...", Use: "uninstall <plugin>...",
Aliases: []string{"rm", "remove"}, Aliases: []string{"rm", "remove"},
Short: "uninstall one or more Helm plugins", Short: "uninstall one or more Helm plugins",
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return compListPlugins(toComplete), cobra.ShellCompDirectiveNoFileComp
},
PreRunE: func(cmd *cobra.Command, args []string) error { PreRunE: func(cmd *cobra.Command, args []string) error {
return o.complete(args) return o.complete(args)
}, },
@ -46,15 +51,6 @@ func newPluginUninstallCmd(out io.Writer) *cobra.Command {
return o.run(out) return o.run(out)
}, },
} }
// Function providing dynamic auto-completion
completion.RegisterValidArgsFunc(cmd, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) {
if len(args) != 0 {
return nil, completion.BashCompDirectiveNoFileComp
}
return compListPlugins(toComplete), completion.BashCompDirectiveNoFileComp
})
return cmd return cmd
} }

@ -24,7 +24,6 @@ import (
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"helm.sh/helm/v3/internal/completion"
"helm.sh/helm/v3/pkg/plugin" "helm.sh/helm/v3/pkg/plugin"
"helm.sh/helm/v3/pkg/plugin/installer" "helm.sh/helm/v3/pkg/plugin/installer"
) )
@ -40,6 +39,12 @@ func newPluginUpdateCmd(out io.Writer) *cobra.Command {
Use: "update <plugin>...", Use: "update <plugin>...",
Aliases: []string{"up"}, Aliases: []string{"up"},
Short: "update one or more Helm plugins", Short: "update one or more Helm plugins",
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return compListPlugins(toComplete), cobra.ShellCompDirectiveNoFileComp
},
PreRunE: func(cmd *cobra.Command, args []string) error { PreRunE: func(cmd *cobra.Command, args []string) error {
return o.complete(args) return o.complete(args)
}, },
@ -47,15 +52,6 @@ func newPluginUpdateCmd(out io.Writer) *cobra.Command {
return o.run(out) return o.run(out)
}, },
} }
// Function providing dynamic auto-completion
completion.RegisterValidArgsFunc(cmd, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) {
if len(args) != 0 {
return nil, completion.BashCompDirectiveNoFileComp
}
return compListPlugins(toComplete), completion.BashCompDirectiveNoFileComp
})
return cmd return cmd
} }

@ -19,11 +19,11 @@ package main
import ( import (
"fmt" "fmt"
"io" "io"
"log"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"helm.sh/helm/v3/cmd/helm/require" "helm.sh/helm/v3/cmd/helm/require"
"helm.sh/helm/v3/internal/completion"
"helm.sh/helm/v3/pkg/action" "helm.sh/helm/v3/pkg/action"
) )
@ -51,6 +51,12 @@ func newPullCmd(out io.Writer) *cobra.Command {
Aliases: []string{"fetch"}, Aliases: []string{"fetch"},
Long: pullDesc, Long: pullDesc,
Args: require.MinimumNArgs(1), Args: require.MinimumNArgs(1),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return compListCharts(toComplete, false)
},
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
client.Settings = settings client.Settings = settings
if client.Version == "" && client.Devel { if client.Version == "" && client.Devel {
@ -69,14 +75,6 @@ func newPullCmd(out io.Writer) *cobra.Command {
}, },
} }
// Function providing dynamic auto-completion
completion.RegisterValidArgsFunc(cmd, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) {
if len(args) != 0 {
return nil, completion.BashCompDirectiveNoFileComp
}
return compListCharts(toComplete, false)
})
f := cmd.Flags() 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.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.Untar, "untar", false, "if set to true, will untar the chart after downloading it")
@ -85,5 +83,16 @@ func newPullCmd(out io.Writer) *cobra.Command {
f.StringVarP(&client.DestDir, "destination", "d", ".", "location to write the chart. If this and tardir are specified, tardir is appended to this") f.StringVarP(&client.DestDir, "destination", "d", ".", "location to write the chart. If this and tardir are specified, tardir is appended to this")
addChartPathOptionsFlags(f, &client.ChartPathOptions) addChartPathOptionsFlags(f, &client.ChartPathOptions)
err := cmd.RegisterFlagCompletionFunc("version", func(cmd *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 return cmd
} }

@ -195,3 +195,29 @@ func TestPullCmd(t *testing.T) {
}) })
} }
} }
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 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)
}

@ -24,7 +24,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"helm.sh/helm/v3/cmd/helm/require" "helm.sh/helm/v3/cmd/helm/require"
"helm.sh/helm/v3/internal/completion"
"helm.sh/helm/v3/pkg/action" "helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/cli/output" "helm.sh/helm/v3/pkg/cli/output"
) )
@ -46,6 +45,12 @@ func newReleaseTestCmd(cfg *action.Configuration, out io.Writer) *cobra.Command
Short: "run tests for a release", Short: "run tests for a release",
Long: releaseTestHelp, Long: releaseTestHelp,
Args: require.ExactArgs(1), Args: require.ExactArgs(1),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return compListReleases(toComplete, cfg)
},
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
client.Namespace = settings.Namespace() client.Namespace = settings.Namespace()
rel, runErr := client.Run(args[0]) rel, runErr := client.Run(args[0])
@ -72,14 +77,6 @@ func newReleaseTestCmd(cfg *action.Configuration, out io.Writer) *cobra.Command
}, },
} }
// Function providing dynamic auto-completion
completion.RegisterValidArgsFunc(cmd, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) {
if len(args) != 0 {
return nil, completion.BashCompDirectiveNoFileComp
}
return compListReleases(toComplete, cfg)
})
f := cmd.Flags() f := cmd.Flags()
f.DurationVar(&client.Timeout, "timeout", 300*time.Second, "time to wait for any individual Kubernetes operation (like Jobs for hooks)") 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.BoolVar(&outputLogs, "logs", false, "dump the logs from test pods (this runs after all tests are complete, but before any cleanup)")

@ -130,6 +130,9 @@ func (o *repoAddOptions) run(out io.Writer) error {
return err return err
} }
if o.repoCache != "" {
r.CachePath = o.repoCache
}
if _, err := r.DownloadIndexFile(); err != nil { if _, err := r.DownloadIndexFile(); err != nil {
return errors.Wrapf(err, "looks like %q is not a valid chart repository or cannot be reached", o.url) return errors.Wrapf(err, "looks like %q is not a valid chart repository or cannot be reached", o.url)
} }

@ -38,7 +38,7 @@ func newRepoListCmd(out io.Writer) *cobra.Command {
Args: require.NoArgs, Args: require.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
f, err := repo.LoadFile(settings.RepositoryConfig) f, err := repo.LoadFile(settings.RepositoryConfig)
if isNotExist(err) || len(f.Repositories) == 0 { if isNotExist(err) || (len(f.Repositories) == 0 && !(outfmt == output.JSON || outfmt == output.YAML)) {
return errors.New("no repositories to show") return errors.New("no repositories to show")
} }

@ -26,7 +26,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"helm.sh/helm/v3/cmd/helm/require" "helm.sh/helm/v3/cmd/helm/require"
"helm.sh/helm/v3/internal/completion"
"helm.sh/helm/v3/pkg/helmpath" "helm.sh/helm/v3/pkg/helmpath"
"helm.sh/helm/v3/pkg/repo" "helm.sh/helm/v3/pkg/repo"
) )
@ -45,6 +44,9 @@ func newRepoRemoveCmd(out io.Writer) *cobra.Command {
Aliases: []string{"rm"}, Aliases: []string{"rm"},
Short: "remove one or more chart repositories", Short: "remove one or more chart repositories",
Args: require.MinimumNArgs(1), Args: require.MinimumNArgs(1),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return compListRepos(toComplete, args), cobra.ShellCompDirectiveNoFileComp
},
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
o.repoFile = settings.RepositoryConfig o.repoFile = settings.RepositoryConfig
o.repoCache = settings.RepositoryCache o.repoCache = settings.RepositoryCache
@ -52,12 +54,6 @@ func newRepoRemoveCmd(out io.Writer) *cobra.Command {
return o.run(out) return o.run(out)
}, },
} }
// Function providing dynamic auto-completion
completion.RegisterValidArgsFunc(cmd, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) {
return compListRepos(toComplete, args), completion.BashCompDirectiveNoFileComp
})
return cmd return cmd
} }

@ -37,8 +37,9 @@ Information is cached locally, where it is used by commands like 'helm search'.
var errNoRepositories = errors.New("no repositories found. You must add one before updating") var errNoRepositories = errors.New("no repositories found. You must add one before updating")
type repoUpdateOptions struct { type repoUpdateOptions struct {
update func([]*repo.ChartRepository, io.Writer) update func([]*repo.ChartRepository, io.Writer)
repoFile string repoFile string
repoCache string
} }
func newRepoUpdateCmd(out io.Writer) *cobra.Command { func newRepoUpdateCmd(out io.Writer) *cobra.Command {
@ -52,6 +53,7 @@ func newRepoUpdateCmd(out io.Writer) *cobra.Command {
Args: require.NoArgs, Args: require.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
o.repoFile = settings.RepositoryConfig o.repoFile = settings.RepositoryConfig
o.repoCache = settings.RepositoryCache
return o.run(out) return o.run(out)
}, },
} }
@ -69,6 +71,9 @@ func (o *repoUpdateOptions) run(out io.Writer) error {
if err != nil { if err != nil {
return err return err
} }
if o.repoCache != "" {
r.CachePath = o.repoCache
}
repos = append(repos, r) repos = append(repos, r)
} }

@ -19,6 +19,8 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"io" "io"
"os"
"path/filepath"
"strings" "strings"
"testing" "testing"
@ -50,6 +52,25 @@ func TestUpdateCmd(t *testing.T) {
} }
} }
func TestUpdateCustomCacheCmd(t *testing.T) {
var out bytes.Buffer
rootDir := ensure.TempDir(t)
cachePath := filepath.Join(rootDir, "updcustomcache")
_ = os.Mkdir(cachePath, os.ModePerm)
defer os.RemoveAll(cachePath)
o := &repoUpdateOptions{
update: updateCharts,
repoFile: "testdata/repositories.yaml",
repoCache: cachePath,
}
if err := o.run(&out); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Join(cachePath, "charts-index.yaml")); err != nil {
t.Fatalf("error finding created index file in custom cache: %#v", err)
}
}
func TestUpdateCharts(t *testing.T) { func TestUpdateCharts(t *testing.T) {
defer resetEnv()() defer resetEnv()()
defer ensure.HelmHome(t)() defer ensure.HelmHome(t)()

@ -25,7 +25,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"helm.sh/helm/v3/cmd/helm/require" "helm.sh/helm/v3/cmd/helm/require"
"helm.sh/helm/v3/internal/completion"
"helm.sh/helm/v3/pkg/action" "helm.sh/helm/v3/pkg/action"
) )
@ -47,6 +46,17 @@ func newRollbackCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
Short: "roll back a release to a previous revision", Short: "roll back a release to a previous revision",
Long: rollbackDesc, Long: rollbackDesc,
Args: require.MinimumNArgs(1), Args: require.MinimumNArgs(1),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 {
return compListReleases(toComplete, cfg)
}
if len(args) == 1 {
return compListRevisions(toComplete, cfg, args[0])
}
return nil, cobra.ShellCompDirectiveNoFileComp
},
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
if len(args) > 1 { if len(args) > 1 {
ver, err := strconv.Atoi(args[1]) ver, err := strconv.Atoi(args[1])
@ -65,14 +75,6 @@ func newRollbackCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
}, },
} }
// Function providing dynamic auto-completion
completion.RegisterValidArgsFunc(cmd, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) {
if len(args) != 0 {
return nil, completion.BashCompDirectiveNoFileComp
}
return compListReleases(toComplete, cfg)
})
f := cmd.Flags() f := cmd.Flags()
f.BoolVar(&client.DryRun, "dry-run", false, "simulate a rollback") f.BoolVar(&client.DryRun, "dry-run", false, "simulate a rollback")
f.BoolVar(&client.Recreate, "recreate-pods", false, "performs pods restart for the resource if applicable") f.BoolVar(&client.Recreate, "recreate-pods", false, "performs pods restart for the resource if applicable")

@ -68,3 +68,39 @@ func TestRollbackCmd(t *testing.T) {
}} }}
runTestCmd(t, tests) runTestCmd(t, tests)
} }
func TestRollbackRevisionCompletion(t *testing.T) {
mk := func(name string, vers int, status release.Status) *release.Release {
return release.Mock(&release.MockReleaseOptions{
Name: name,
Version: vers,
Status: status,
})
}
releases := []*release.Release{
mk("musketeers", 11, release.StatusDeployed),
mk("musketeers", 10, release.StatusSuperseded),
mk("musketeers", 9, release.StatusSuperseded),
mk("musketeers", 8, release.StatusSuperseded),
mk("carabins", 1, release.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)
}

@ -20,6 +20,7 @@ import (
"context" "context"
"fmt" "fmt"
"io" "io"
"log"
"strings" "strings"
"github.com/spf13/cobra" "github.com/spf13/cobra"
@ -27,7 +28,6 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/clientcmd" "k8s.io/client-go/tools/clientcmd"
"helm.sh/helm/v3/internal/completion"
"helm.sh/helm/v3/internal/experimental/registry" "helm.sh/helm/v3/internal/experimental/registry"
"helm.sh/helm/v3/pkg/action" "helm.sh/helm/v3/pkg/action"
) )
@ -43,55 +43,49 @@ Common actions for Helm:
Environment variables: Environment variables:
+------------------+--------------------------------------------------------------------------------------------------------+ | Name | Description |
| Name | Description | |------------------------------------|-----------------------------------------------------------------------------------|
+------------------+--------------------------------------------------------------------------------------------------------+ | $HELM_CACHE_HOME | set an alternative location for storing cached files. |
| $XDG_CACHE_HOME | set an alternative location for storing cached files. | | $HELM_CONFIG_HOME | set an alternative location for storing Helm configuration. |
| $XDG_CONFIG_HOME | set an alternative location for storing Helm configuration. | | $HELM_DATA_HOME | set an alternative location for storing Helm data. |
| $XDG_DATA_HOME | set an alternative location for storing Helm data. | | $HELM_DRIVER | set the backend storage driver. Values are: configmap, secret, memory, postgres |
| $HELM_DRIVER | set the backend storage driver. Values are: configmap, secret, memory, postgres | | $HELM_DRIVER_SQL_CONNECTION_STRING | set the connection string the SQL storage driver should use. |
| $HELM_DRIVER_SQL_CONNECTION_STRING | set the connection string the SQL storage driver should use. | | $HELM_NO_PLUGINS | disable plugins. Set HELM_NO_PLUGINS=1 to disable plugins. |
| $HELM_NO_PLUGINS | disable plugins. Set HELM_NO_PLUGINS=1 to disable plugins. | | $KUBECONFIG | set an alternative Kubernetes configuration file (default "~/.kube/config") |
| $KUBECONFIG | set an alternative Kubernetes configuration file (default "~/.kube/config") |
+------------------+--------------------------------------------------------------------------------------------------------+
Helm stores configuration based on the XDG base directory specification, so Helm stores cache, configuration, and data based on the following configuration order:
- cached files are stored in $XDG_CACHE_HOME/helm - If a HELM_*_HOME environment variable is set, it will be used
- configuration is stored in $XDG_CONFIG_HOME/helm - Otherwise, on systems supporting the XDG base directory specification, the XDG variables will be used
- data is stored in $XDG_DATA_HOME/helm - When no other location is set a default location will be used based on the operating system
By default, the default directories depend on the Operating System. The defaults are listed below: By default, the default directories depend on the Operating System. The defaults are listed below:
+------------------+---------------------------+--------------------------------+-------------------------+
| Operating System | Cache Path | Configuration Path | Data Path | | Operating System | Cache Path | Configuration Path | Data Path |
+------------------+---------------------------+--------------------------------+-------------------------+ |------------------|---------------------------|--------------------------------|-------------------------|
| Linux | $HOME/.cache/helm | $HOME/.config/helm | $HOME/.local/share/helm | | Linux | $HOME/.cache/helm | $HOME/.config/helm | $HOME/.local/share/helm |
| macOS | $HOME/Library/Caches/helm | $HOME/Library/Preferences/helm | $HOME/Library/helm | | macOS | $HOME/Library/Caches/helm | $HOME/Library/Preferences/helm | $HOME/Library/helm |
| Windows | %TEMP%\helm | %APPDATA%\helm | %APPDATA%\helm | | Windows | %TEMP%\helm | %APPDATA%\helm | %APPDATA%\helm |
+------------------+---------------------------+--------------------------------+-------------------------+
` `
func newRootCmd(actionConfig *action.Configuration, out io.Writer, args []string) *cobra.Command { func newRootCmd(actionConfig *action.Configuration, out io.Writer, args []string) (*cobra.Command, error) {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "helm", Use: "helm",
Short: "The Helm package manager for Kubernetes.", Short: "The Helm package manager for Kubernetes.",
Long: globalUsage, Long: globalUsage,
SilenceUsage: true, SilenceUsage: true,
BashCompletionFunction: completion.GetBashCustomFunction(),
} }
flags := cmd.PersistentFlags() flags := cmd.PersistentFlags()
settings.AddFlags(flags) settings.AddFlags(flags)
// Setup shell completion for the namespace flag // Setup shell completion for the namespace flag
flag := flags.Lookup("namespace") err := cmd.RegisterFlagCompletionFunc("namespace", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
completion.RegisterFlagCompletionFunc(flag, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) {
if client, err := actionConfig.KubernetesClientSet(); err == nil { if client, err := actionConfig.KubernetesClientSet(); err == nil {
// Choose a long enough timeout that the user notices somethings is not working // Choose a long enough timeout that the user notices somethings is not working
// but short enough that the user is not made to wait very long // but short enough that the user is not made to wait very long
to := int64(3) to := int64(3)
completion.CompDebugln(fmt.Sprintf("About to call kube client for namespaces with timeout of: %d", to)) cobra.CompDebugln(fmt.Sprintf("About to call kube client for namespaces with timeout of: %d", to), settings.Debug)
nsNames := []string{} nsNames := []string{}
if namespaces, err := client.CoreV1().Namespaces().List(context.Background(), metav1.ListOptions{TimeoutSeconds: &to}); err == nil { if namespaces, err := client.CoreV1().Namespaces().List(context.Background(), metav1.ListOptions{TimeoutSeconds: &to}); err == nil {
@ -100,16 +94,19 @@ func newRootCmd(actionConfig *action.Configuration, out io.Writer, args []string
nsNames = append(nsNames, ns.Name) nsNames = append(nsNames, ns.Name)
} }
} }
return nsNames, completion.BashCompDirectiveNoFileComp return nsNames, cobra.ShellCompDirectiveNoFileComp
} }
} }
return nil, completion.BashCompDirectiveDefault return nil, cobra.ShellCompDirectiveDefault
}) })
if err != nil {
log.Fatal(err)
}
// Setup shell completion for the kube-context flag // Setup shell completion for the kube-context flag
flag = flags.Lookup("kube-context") err = cmd.RegisterFlagCompletionFunc("kube-context", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
completion.RegisterFlagCompletionFunc(flag, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) { cobra.CompDebugln("About to get the different kube-contexts", settings.Debug)
completion.CompDebugln("About to get the different kube-contexts")
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules() loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
if len(settings.KubeConfig) > 0 { if len(settings.KubeConfig) > 0 {
@ -124,11 +121,15 @@ func newRootCmd(actionConfig *action.Configuration, out io.Writer, args []string
ctxs = append(ctxs, name) ctxs = append(ctxs, name)
} }
} }
return ctxs, completion.BashCompDirectiveNoFileComp return ctxs, cobra.ShellCompDirectiveNoFileComp
} }
return nil, completion.BashCompDirectiveNoFileComp return nil, cobra.ShellCompDirectiveNoFileComp
}) })
if err != nil {
log.Fatal(err)
}
// We can safely ignore any errors that flags.Parse encounters since // We can safely ignore any errors that flags.Parse encounters since
// those errors will be caught later during the call to cmd.Execution. // those errors will be caught later during the call to cmd.Execution.
// This call is required to gather configuration information prior to // This call is required to gather configuration information prior to
@ -168,19 +169,16 @@ func newRootCmd(actionConfig *action.Configuration, out io.Writer, args []string
// Hidden documentation generator command: 'helm docs' // Hidden documentation generator command: 'helm docs'
newDocsCmd(out), newDocsCmd(out),
// Setup the special hidden __complete command to allow for dynamic auto-completion
completion.NewCompleteCmd(settings, out),
) )
// Add *experimental* subcommands // Add *experimental* subcommands
registryClient, err := registry.NewClient( registryClient, err := registry.NewClient(
registry.ClientOptDebug(settings.Debug), registry.ClientOptDebug(settings.Debug),
registry.ClientOptWriter(out), registry.ClientOptWriter(out),
registry.ClientOptCredentialsFile(settings.RegistryConfig),
) )
if err != nil { if err != nil {
// TODO: don't panic here, refactor newRootCmd to return error return nil, err
panic(err)
} }
actionConfig.RegistryClient = registryClient actionConfig.RegistryClient = registryClient
cmd.AddCommand( cmd.AddCommand(
@ -191,5 +189,5 @@ func newRootCmd(actionConfig *action.Configuration, out io.Writer, args []string
// Find and add plugins // Find and add plugins
loadPlugins(cmd, out) loadPlugins(cmd, out)
return cmd return cmd, nil
} }

@ -55,6 +55,24 @@ func TestRootCmd(t *testing.T) {
envvars: map[string]string{xdg.DataHomeEnvVar: "/bar"}, envvars: map[string]string{xdg.DataHomeEnvVar: "/bar"},
dataPath: "/bar/helm", 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 { for _, tt := range tests {

@ -32,7 +32,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"helm.sh/helm/v3/cmd/helm/search" "helm.sh/helm/v3/cmd/helm/search"
"helm.sh/helm/v3/internal/completion"
"helm.sh/helm/v3/pkg/cli/output" "helm.sh/helm/v3/pkg/cli/output"
"helm.sh/helm/v3/pkg/helmpath" "helm.sh/helm/v3/pkg/helmpath"
"helm.sh/helm/v3/pkg/repo" "helm.sh/helm/v3/pkg/repo"
@ -290,8 +289,8 @@ func compListChartsOfRepo(repoName string, prefix string) []string {
// Provide dynamic auto-completion for commands that operate on charts (e.g., helm show) // 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) // When true, the includeFiles argument indicates that completion should include local files (e.g., local charts)
func compListCharts(toComplete string, includeFiles bool) ([]string, completion.BashCompDirective) { func compListCharts(toComplete string, includeFiles bool) ([]string, cobra.ShellCompDirective) {
completion.CompDebugln(fmt.Sprintf("compListCharts with toComplete %s", toComplete)) cobra.CompDebugln(fmt.Sprintf("compListCharts with toComplete %s", toComplete), settings.Debug)
noSpace := false noSpace := false
noFile := false noFile := false
@ -312,7 +311,7 @@ func compListCharts(toComplete string, includeFiles bool) ([]string, completion.
noSpace = true noSpace = true
} }
} }
completion.CompDebugln(fmt.Sprintf("Completions after repos: %v", completions)) cobra.CompDebugln(fmt.Sprintf("Completions after repos: %v", completions), settings.Debug)
// Now handle completions for url prefixes // Now handle completions for url prefixes
for _, url := range []string{"https://", "http://", "file://"} { for _, url := range []string{"https://", "http://", "file://"} {
@ -328,7 +327,7 @@ func compListCharts(toComplete string, includeFiles bool) ([]string, completion.
noSpace = true noSpace = true
} }
} }
completion.CompDebugln(fmt.Sprintf("Completions after urls: %v", completions)) cobra.CompDebugln(fmt.Sprintf("Completions after urls: %v", completions), settings.Debug)
// Finally, provide file completion if we need to. // Finally, provide file completion if we need to.
// We only do this if: // We only do this if:
@ -347,22 +346,22 @@ func compListCharts(toComplete string, includeFiles bool) ([]string, completion.
} }
} }
} }
completion.CompDebugln(fmt.Sprintf("Completions after files: %v", completions)) cobra.CompDebugln(fmt.Sprintf("Completions after files: %v", completions), settings.Debug)
// If the user didn't provide any input to completion, // If the user didn't provide any input to completion,
// we provide a hint that a path can also be used // we provide a hint that a path can also be used
if includeFiles && len(toComplete) == 0 { if includeFiles && len(toComplete) == 0 {
completions = append(completions, "./", "/") completions = append(completions, "./", "/")
} }
completion.CompDebugln(fmt.Sprintf("Completions after checking empty input: %v", completions)) cobra.CompDebugln(fmt.Sprintf("Completions after checking empty input: %v", completions), settings.Debug)
directive := completion.BashCompDirectiveDefault directive := cobra.ShellCompDirectiveDefault
if noFile { if noFile {
directive = directive | completion.BashCompDirectiveNoFileComp directive = directive | cobra.ShellCompDirectiveNoFileComp
} }
if noSpace { if noSpace {
directive = directive | completion.BashCompDirectiveNoSpace directive = directive | cobra.ShellCompDirectiveNoSpace
// The completion.BashCompDirective flags do not work for zsh right now. // The cobra.ShellCompDirective flags do not work for zsh right now.
// We handle it ourselves instead. // We handle it ourselves instead.
completions = compEnforceNoSpace(completions) completions = compEnforceNoSpace(completions)
} }
@ -380,7 +379,7 @@ func compEnforceNoSpace(completions []string) []string {
// We only do this if there is a single choice for completion. // We only do this if there is a single choice for completion.
if len(completions) == 1 { if len(completions) == 1 {
completions = append(completions, completions[0]+".") completions = append(completions, completions[0]+".")
completion.CompDebugln(fmt.Sprintf("compEnforceNoSpace: completions now are %v", completions)) cobra.CompDebugln(fmt.Sprintf("compEnforceNoSpace: completions now are %v", completions), settings.Debug)
} }
return completions return completions
} }

@ -19,11 +19,11 @@ package main
import ( import (
"fmt" "fmt"
"io" "io"
"log"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"helm.sh/helm/v3/cmd/helm/require" "helm.sh/helm/v3/cmd/helm/require"
"helm.sh/helm/v3/internal/completion"
"helm.sh/helm/v3/pkg/action" "helm.sh/helm/v3/pkg/action"
) )
@ -63,18 +63,19 @@ func newShowCmd(out io.Writer) *cobra.Command {
} }
// Function providing dynamic auto-completion // Function providing dynamic auto-completion
validArgsFunc := func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) { validArgsFunc := func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 { if len(args) != 0 {
return nil, completion.BashCompDirectiveNoFileComp return nil, cobra.ShellCompDirectiveNoFileComp
} }
return compListCharts(toComplete, true) return compListCharts(toComplete, true)
} }
all := &cobra.Command{ all := &cobra.Command{
Use: "all [CHART]", Use: "all [CHART]",
Short: "shows all information of the chart", Short: "show all information of the chart",
Long: showAllDesc, Long: showAllDesc,
Args: require.ExactArgs(1), Args: require.ExactArgs(1),
ValidArgsFunction: validArgsFunc,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
client.OutputFormat = action.ShowAll client.OutputFormat = action.ShowAll
output, err := runShow(args, client) output, err := runShow(args, client)
@ -87,10 +88,11 @@ func newShowCmd(out io.Writer) *cobra.Command {
} }
valuesSubCmd := &cobra.Command{ valuesSubCmd := &cobra.Command{
Use: "values [CHART]", Use: "values [CHART]",
Short: "shows the chart's values", Short: "show the chart's values",
Long: showValuesDesc, Long: showValuesDesc,
Args: require.ExactArgs(1), Args: require.ExactArgs(1),
ValidArgsFunction: validArgsFunc,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
client.OutputFormat = action.ShowValues client.OutputFormat = action.ShowValues
output, err := runShow(args, client) output, err := runShow(args, client)
@ -103,10 +105,11 @@ func newShowCmd(out io.Writer) *cobra.Command {
} }
chartSubCmd := &cobra.Command{ chartSubCmd := &cobra.Command{
Use: "chart [CHART]", Use: "chart [CHART]",
Short: "shows the chart's definition", Short: "show the chart's definition",
Long: showChartDesc, Long: showChartDesc,
Args: require.ExactArgs(1), Args: require.ExactArgs(1),
ValidArgsFunction: validArgsFunc,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
client.OutputFormat = action.ShowChart client.OutputFormat = action.ShowChart
output, err := runShow(args, client) output, err := runShow(args, client)
@ -119,10 +122,11 @@ func newShowCmd(out io.Writer) *cobra.Command {
} }
readmeSubCmd := &cobra.Command{ readmeSubCmd := &cobra.Command{
Use: "readme [CHART]", Use: "readme [CHART]",
Short: "shows the chart's README", Short: "show the chart's README",
Long: readmeChartDesc, Long: readmeChartDesc,
Args: require.ExactArgs(1), Args: require.ExactArgs(1),
ValidArgsFunction: validArgsFunc,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
client.OutputFormat = action.ShowReadme client.OutputFormat = action.ShowReadme
output, err := runShow(args, client) output, err := runShow(args, client)
@ -136,21 +140,29 @@ func newShowCmd(out io.Writer) *cobra.Command {
cmds := []*cobra.Command{all, readmeSubCmd, valuesSubCmd, chartSubCmd} cmds := []*cobra.Command{all, readmeSubCmd, valuesSubCmd, chartSubCmd}
for _, subCmd := range cmds { for _, subCmd := range cmds {
addShowFlags(showCommand, subCmd, client) addShowFlags(subCmd, client)
showCommand.AddCommand(subCmd)
// Register the completion function for each subcommand
completion.RegisterValidArgsFunc(subCmd, validArgsFunc)
} }
return showCommand return showCommand
} }
func addShowFlags(showCmd *cobra.Command, subCmd *cobra.Command, client *action.Show) { func addShowFlags(subCmd *cobra.Command, client *action.Show) {
f := subCmd.Flags() f := subCmd.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.Devel, "devel", false, "use development versions, too. Equivalent to version '>0.0.0-0'. If --version is set, this is ignored")
addChartPathOptionsFlags(f, &client.ChartPathOptions) addChartPathOptionsFlags(f, &client.ChartPathOptions)
showCmd.AddCommand(subCmd)
err := subCmd.RegisterFlagCompletionFunc("version", func(cmd *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)
}
} }
func runShow(args []string, client *action.Show) (string, error) { func runShow(args []string, client *action.Show) (string, error) {

@ -80,3 +80,41 @@ func TestShowPreReleaseChart(t *testing.T) {
}) })
} }
} }
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 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)
}

@ -19,13 +19,13 @@ package main
import ( import (
"fmt" "fmt"
"io" "io"
"log"
"strings" "strings"
"time" "time"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"helm.sh/helm/v3/cmd/helm/require" "helm.sh/helm/v3/cmd/helm/require"
"helm.sh/helm/v3/internal/completion"
"helm.sh/helm/v3/pkg/action" "helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/chartutil" "helm.sh/helm/v3/pkg/chartutil"
"helm.sh/helm/v3/pkg/cli/output" "helm.sh/helm/v3/pkg/cli/output"
@ -50,9 +50,15 @@ func newStatusCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "status RELEASE_NAME", Use: "status RELEASE_NAME",
Short: "displays the status of the named release", Short: "display the status of the named release",
Long: statusHelp, Long: statusHelp,
Args: require.ExactArgs(1), Args: require.ExactArgs(1),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return compListReleases(toComplete, cfg)
},
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
rel, err := client.Run(args[0]) rel, err := client.Run(args[0])
if err != nil { if err != nil {
@ -66,25 +72,21 @@ func newStatusCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
}, },
} }
// Function providing dynamic auto-completion f := cmd.Flags()
completion.RegisterValidArgsFunc(cmd, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) {
if len(args) != 0 {
return nil, completion.BashCompDirectiveNoFileComp
}
return compListReleases(toComplete, cfg)
})
f := cmd.PersistentFlags()
f.IntVar(&client.Version, "revision", 0, "if set, display the status of the named release with revision") f.IntVar(&client.Version, "revision", 0, "if set, display the status of the named release with revision")
flag := f.Lookup("revision")
completion.RegisterFlagCompletionFunc(flag, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) { err := cmd.RegisterFlagCompletionFunc("revision", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 1 { if len(args) == 1 {
return compListRevisions(cfg, args[0]) return compListRevisions(toComplete, cfg, args[0])
} }
return nil, completion.BashCompDirectiveNoFileComp return nil, cobra.ShellCompDirectiveNoFileComp
}) })
if err != nil {
log.Fatal(err)
}
bindOutputFlag(cmd, &outfmt) bindOutputFlag(cmd, &outfmt)
return cmd return cmd

@ -28,7 +28,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"helm.sh/helm/v3/cmd/helm/require" "helm.sh/helm/v3/cmd/helm/require"
"helm.sh/helm/v3/internal/completion"
"helm.sh/helm/v3/pkg/action" "helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/chartutil" "helm.sh/helm/v3/pkg/chartutil"
"helm.sh/helm/v3/pkg/cli/values" "helm.sh/helm/v3/pkg/cli/values"
@ -56,6 +55,9 @@ func newTemplateCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
Short: "locally render templates", Short: "locally render templates",
Long: templateDesc, Long: templateDesc,
Args: require.MinimumNArgs(1), Args: require.MinimumNArgs(1),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return compInstall(args, toComplete, client)
},
RunE: func(_ *cobra.Command, args []string) error { RunE: func(_ *cobra.Command, args []string) error {
client.DryRun = true client.DryRun = true
client.ReleaseName = "RELEASE-NAME" client.ReleaseName = "RELEASE-NAME"
@ -78,12 +80,6 @@ func newTemplateCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
var manifests bytes.Buffer var manifests bytes.Buffer
fmt.Fprintln(&manifests, strings.TrimSpace(rel.Manifest)) fmt.Fprintln(&manifests, strings.TrimSpace(rel.Manifest))
if !client.DisableHooks {
for _, m := range rel.Hooks {
fmt.Fprintf(&manifests, "---\n# Source: %s\n%s\n", m.Path, m.Manifest)
}
}
// if we have a list of files to render, then check that each of the // if we have a list of files to render, then check that each of the
// provided files exists in the chart. // provided files exists in the chart.
if len(showFiles) > 0 { if len(showFiles) > 0 {
@ -100,6 +96,8 @@ func newTemplateCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
var manifestsToRender []string var manifestsToRender []string
for _, f := range showFiles { for _, f := range showFiles {
missing := true missing := true
// Use linux-style filepath separators to unify user's input path
f = filepath.ToSlash(f)
for _, manifestKey := range manifestsKeys { for _, manifestKey := range manifestsKeys {
manifest := splitManifests[manifestKey] manifest := splitManifests[manifestKey]
submatch := manifestNameRegex.FindStringSubmatch(manifest) submatch := manifestNameRegex.FindStringSubmatch(manifest)
@ -110,7 +108,9 @@ func newTemplateCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
// manifest.Name is rendered using linux-style filepath separators on Windows as // manifest.Name is rendered using linux-style filepath separators on Windows as
// well as macOS/linux. // well as macOS/linux.
manifestPathSplit := strings.Split(manifestName, "/") manifestPathSplit := strings.Split(manifestName, "/")
manifestPath := filepath.Join(manifestPathSplit...) // 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 // if the filepath provided matches a manifest path in the
// chart, render that manifest // chart, render that manifest
@ -136,13 +136,8 @@ func newTemplateCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
}, },
} }
// Function providing dynamic auto-completion
completion.RegisterValidArgsFunc(cmd, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) {
return compInstall(args, toComplete, client)
})
f := cmd.Flags() f := cmd.Flags()
addInstallFlags(f, client, valueOpts) addInstallFlags(cmd, f, client, valueOpts)
f.StringArrayVarP(&showFiles, "show-only", "s", []string{}, "only show manifests rendered from the given templates") f.StringArrayVarP(&showFiles, "show-only", "s", []string{}, "only show manifests rendered from the given templates")
f.StringVar(&client.OutputDir, "output-dir", "", "writes the executed templates to files in output-dir instead of stdout") f.StringVar(&client.OutputDir, "output-dir", "", "writes the executed templates to files in output-dir instead of stdout")
f.BoolVar(&validate, "validate", false, "validate your manifests against the Kubernetes cluster you are currently pointing at. This is the same validation performed on an install") f.BoolVar(&validate, "validate", false, "validate your manifests against the Kubernetes cluster you are currently pointing at. This is the same validation performed on an install")

@ -22,7 +22,7 @@ import (
"testing" "testing"
) )
var chartPath = "./../../pkg/chartutil/testdata/subpop/charts/subchart1" var chartPath = "testdata/testcharts/subchart"
func TestTemplateCmd(t *testing.T) { func TestTemplateCmd(t *testing.T) {
tests := []cmdTestCase{ tests := []cmdTestCase{
@ -124,3 +124,33 @@ func TestTemplateCmd(t *testing.T) {
} }
runTestCmd(t, tests) 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)
}

@ -0,0 +1,3 @@
apiVersion: v1
entries: {}
generated: "2020-06-23T10:01:59.2530763-07:00"

@ -1,4 +1,3 @@
WARNING: This chart is deprecated
NAME: aeneas NAME: aeneas
LAST DEPLOYED: Fri Sep 2 22:04:05 1977 LAST DEPLOYED: Fri Sep 2 22:04:05 1977
NAMESPACE: default NAMESPACE: default

@ -2,3 +2,4 @@ table
json json
yaml yaml
:0 :0
Completion ended with directive: ShellCompDirectiveDefault

@ -3,3 +3,4 @@ Namespace: default
Num args received: 1 Num args received: 1
Args received: Args received:
:4 :4
Completion ended with directive: ShellCompDirectiveNoFileComp

@ -3,3 +3,4 @@ Namespace: default
Num args received: 2 Num args received: 2
Args received: --myflag Args received: --myflag
:4 :4
Completion ended with directive: ShellCompDirectiveNoFileComp

@ -3,3 +3,4 @@ Namespace: mynamespace
Num args received: 2 Num args received: 2
Args received: --myflag start Args received: --myflag start
:2 :2
Completion ended with directive: ShellCompDirectiveNoSpace

@ -3,3 +3,4 @@ Namespace: mynamespace
Num args received: 1 Num args received: 1
Args received: Args received:
:2 :2
Completion ended with directive: ShellCompDirectiveNoSpace

@ -3,3 +3,4 @@ Namespace: default
Num args received: 1 Num args received: 1
Args received: Args received:
:0 :0
Completion ended with directive: ShellCompDirectiveDefault

@ -3,3 +3,4 @@ Namespace: mynamespace
Num args received: 1 Num args received: 1
Args received: Args received:
:0 :0
Completion ended with directive: ShellCompDirectiveDefault

@ -2,4 +2,5 @@
9 9
10 10
11 11
:0 :4
Completion ended with directive: ShellCompDirectiveNoFileComp

@ -1 +1,2 @@
:4 :4
Completion ended with directive: ShellCompDirectiveNoFileComp

@ -0,0 +1,4 @@
carabins
musketeers
:4
Completion ended with directive: ShellCompDirectiveNoFileComp

@ -0,0 +1,2 @@
:4
Completion ended with directive: ShellCompDirectiveNoFileComp

@ -1,4 +1,4 @@
Error: values don't meet the specifications of the schema(s) in the following chart(s): Error: values don't meet the specifications of the schema(s) in the following chart(s):
empty: empty:
- age: Must be greater than or equal to 0/1 - age: Must be greater than or equal to 0

@ -1,5 +1,5 @@
Error: values don't meet the specifications of the schema(s) in the following chart(s): Error: values don't meet the specifications of the schema(s) in the following chart(s):
empty: empty:
- (root): employmentInfo is required - (root): employmentInfo is required
- age: Must be greater than or equal to 0/1 - age: Must be greater than or equal to 0

@ -1,3 +1,4 @@
aramis aramis
athos athos
:4 :4
Completion ended with directive: ShellCompDirectiveNoFileComp

@ -1 +1,2 @@
:4 :4
Completion ended with directive: ShellCompDirectiveNoFileComp

@ -1,4 +1,4 @@
Error: values don't meet the specifications of the schema(s) in the following chart(s): Error: values don't meet the specifications of the schema(s) in the following chart(s):
subchart-with-schema: subchart-with-schema:
- age: Must be greater than or equal to 0/1 - age: Must be greater than or equal to 0

@ -1,34 +1,34 @@
--- ---
# Source: subchart1/templates/subdir/serviceaccount.yaml # Source: subchart/templates/subdir/serviceaccount.yaml
apiVersion: v1 apiVersion: v1
kind: ServiceAccount kind: ServiceAccount
metadata: metadata:
name: subchart1-sa name: subchart-sa
--- ---
# Source: subchart1/templates/subdir/role.yaml # Source: subchart/templates/subdir/role.yaml
apiVersion: rbac.authorization.k8s.io/v1 apiVersion: rbac.authorization.k8s.io/v1
kind: Role kind: Role
metadata: metadata:
name: subchart1-role name: subchart-role
rules: rules:
- resources: ["*"] - resources: ["*"]
verbs: ["get","list","watch"] verbs: ["get","list","watch"]
--- ---
# Source: subchart1/templates/subdir/rolebinding.yaml # Source: subchart/templates/subdir/rolebinding.yaml
apiVersion: rbac.authorization.k8s.io/v1 apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding kind: RoleBinding
metadata: metadata:
name: subchart1-binding name: subchart-binding
roleRef: roleRef:
apiGroup: rbac.authorization.k8s.io apiGroup: rbac.authorization.k8s.io
kind: Role kind: Role
name: subchart1-role name: subchart-role
subjects: subjects:
- kind: ServiceAccount - kind: ServiceAccount
name: subchart1-sa name: subchart-sa
namespace: default namespace: default
--- ---
# Source: subchart1/charts/subcharta/templates/service.yaml # Source: subchart/charts/subcharta/templates/service.yaml
apiVersion: v1 apiVersion: v1
kind: Service kind: Service
metadata: metadata:
@ -45,7 +45,7 @@ spec:
selector: selector:
app.kubernetes.io/name: subcharta app.kubernetes.io/name: subcharta
--- ---
# Source: subchart1/charts/subchartb/templates/service.yaml # Source: subchart/charts/subchartb/templates/service.yaml
apiVersion: v1 apiVersion: v1
kind: Service kind: Service
metadata: metadata:
@ -62,17 +62,17 @@ spec:
selector: selector:
app.kubernetes.io/name: subchartb app.kubernetes.io/name: subchartb
--- ---
# Source: subchart1/templates/service.yaml # Source: subchart/templates/service.yaml
apiVersion: v1 apiVersion: v1
kind: Service kind: Service
metadata: metadata:
name: subchart1 name: subchart
labels: labels:
helm.sh/chart: "subchart1-0.1.0" helm.sh/chart: "subchart-0.1.0"
app.kubernetes.io/instance: "foobar-YWJj-baz" app.kubernetes.io/instance: "foobar-YWJj-baz"
kube-version/major: "1" kube-version/major: "1"
kube-version/minor: "16" kube-version/minor: "18"
kube-version/version: "v1.16.0" kube-version/version: "v1.18.0"
spec: spec:
type: ClusterIP type: ClusterIP
ports: ports:
@ -81,4 +81,4 @@ spec:
protocol: TCP protocol: TCP
name: nginx name: nginx
selector: selector:
app.kubernetes.io/name: subchart1 app.kubernetes.io/name: subchart

@ -1,34 +1,34 @@
--- ---
# Source: subchart1/templates/subdir/serviceaccount.yaml # Source: subchart/templates/subdir/serviceaccount.yaml
apiVersion: v1 apiVersion: v1
kind: ServiceAccount kind: ServiceAccount
metadata: metadata:
name: subchart1-sa name: subchart-sa
--- ---
# Source: subchart1/templates/subdir/role.yaml # Source: subchart/templates/subdir/role.yaml
apiVersion: rbac.authorization.k8s.io/v1 apiVersion: rbac.authorization.k8s.io/v1
kind: Role kind: Role
metadata: metadata:
name: subchart1-role name: subchart-role
rules: rules:
- resources: ["*"] - resources: ["*"]
verbs: ["get","list","watch"] verbs: ["get","list","watch"]
--- ---
# Source: subchart1/templates/subdir/rolebinding.yaml # Source: subchart/templates/subdir/rolebinding.yaml
apiVersion: rbac.authorization.k8s.io/v1 apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding kind: RoleBinding
metadata: metadata:
name: subchart1-binding name: subchart-binding
roleRef: roleRef:
apiGroup: rbac.authorization.k8s.io apiGroup: rbac.authorization.k8s.io
kind: Role kind: Role
name: subchart1-role name: subchart-role
subjects: subjects:
- kind: ServiceAccount - kind: ServiceAccount
name: subchart1-sa name: subchart-sa
namespace: default namespace: default
--- ---
# Source: subchart1/charts/subcharta/templates/service.yaml # Source: subchart/charts/subcharta/templates/service.yaml
apiVersion: v1 apiVersion: v1
kind: Service kind: Service
metadata: metadata:
@ -45,7 +45,7 @@ spec:
selector: selector:
app.kubernetes.io/name: subcharta app.kubernetes.io/name: subcharta
--- ---
# Source: subchart1/charts/subchartb/templates/service.yaml # Source: subchart/charts/subchartb/templates/service.yaml
apiVersion: v1 apiVersion: v1
kind: Service kind: Service
metadata: metadata:
@ -62,17 +62,17 @@ spec:
selector: selector:
app.kubernetes.io/name: subchartb app.kubernetes.io/name: subchartb
--- ---
# Source: subchart1/templates/service.yaml # Source: subchart/templates/service.yaml
apiVersion: v1 apiVersion: v1
kind: Service kind: Service
metadata: metadata:
name: subchart1 name: subchart
labels: labels:
helm.sh/chart: "subchart1-0.1.0" helm.sh/chart: "subchart-0.1.0"
app.kubernetes.io/instance: "RELEASE-NAME" app.kubernetes.io/instance: "RELEASE-NAME"
kube-version/major: "1" kube-version/major: "1"
kube-version/minor: "16" kube-version/minor: "18"
kube-version/version: "v1.16.0" kube-version/version: "v1.18.0"
spec: spec:
type: ClusterIP type: ClusterIP
ports: ports:
@ -81,4 +81,4 @@ spec:
protocol: TCP protocol: TCP
name: apache name: apache
selector: selector:
app.kubernetes.io/name: subchart1 app.kubernetes.io/name: subchart

@ -1,23 +1,23 @@
--- ---
# Source: subchart1/templates/subdir/role.yaml # Source: subchart/templates/subdir/role.yaml
apiVersion: rbac.authorization.k8s.io/v1 apiVersion: rbac.authorization.k8s.io/v1
kind: Role kind: Role
metadata: metadata:
name: subchart1-role name: subchart-role
rules: rules:
- resources: ["*"] - resources: ["*"]
verbs: ["get","list","watch"] verbs: ["get","list","watch"]
--- ---
# Source: subchart1/templates/subdir/rolebinding.yaml # Source: subchart/templates/subdir/rolebinding.yaml
apiVersion: rbac.authorization.k8s.io/v1 apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding kind: RoleBinding
metadata: metadata:
name: subchart1-binding name: subchart-binding
roleRef: roleRef:
apiGroup: rbac.authorization.k8s.io apiGroup: rbac.authorization.k8s.io
kind: Role kind: Role
name: subchart1-role name: subchart-role
subjects: subjects:
- kind: ServiceAccount - kind: ServiceAccount
name: subchart1-sa name: subchart-sa
namespace: default namespace: default

@ -1,15 +1,15 @@
--- ---
# Source: subchart1/templates/service.yaml # Source: subchart/templates/service.yaml
apiVersion: v1 apiVersion: v1
kind: Service kind: Service
metadata: metadata:
name: subchart1 name: subchart
labels: labels:
helm.sh/chart: "subchart1-0.1.0" helm.sh/chart: "subchart-0.1.0"
app.kubernetes.io/instance: "RELEASE-NAME" app.kubernetes.io/instance: "RELEASE-NAME"
kube-version/major: "1" kube-version/major: "1"
kube-version/minor: "16" kube-version/minor: "18"
kube-version/version: "v1.16.0" kube-version/version: "v1.18.0"
kube-api-version/test: v1 kube-api-version/test: v1
spec: spec:
type: ClusterIP type: ClusterIP
@ -19,9 +19,9 @@ spec:
protocol: TCP protocol: TCP
name: nginx name: nginx
selector: selector:
app.kubernetes.io/name: subchart1 app.kubernetes.io/name: subchart
--- ---
# Source: subchart1/charts/subcharta/templates/service.yaml # Source: subchart/charts/subcharta/templates/service.yaml
apiVersion: v1 apiVersion: v1
kind: Service kind: Service
metadata: metadata:

@ -1,15 +1,15 @@
--- ---
# Source: subchart1/templates/service.yaml # Source: subchart/templates/service.yaml
apiVersion: v1 apiVersion: v1
kind: Service kind: Service
metadata: metadata:
name: subchart1 name: subchart
labels: labels:
helm.sh/chart: "subchart1-0.1.0" helm.sh/chart: "subchart-0.1.0"
app.kubernetes.io/instance: "RELEASE-NAME" app.kubernetes.io/instance: "RELEASE-NAME"
kube-version/major: "1" kube-version/major: "1"
kube-version/minor: "16" kube-version/minor: "18"
kube-version/version: "v1.16.0" kube-version/version: "v1.18.0"
kube-api-version/test: v1 kube-api-version/test: v1
spec: spec:
type: ClusterIP type: ClusterIP
@ -19,4 +19,4 @@ spec:
protocol: TCP protocol: TCP
name: nginx name: nginx
selector: selector:
app.kubernetes.io/name: subchart1 app.kubernetes.io/name: subchart

@ -1,34 +1,34 @@
--- ---
# Source: subchart1/templates/subdir/serviceaccount.yaml # Source: subchart/templates/subdir/serviceaccount.yaml
apiVersion: v1 apiVersion: v1
kind: ServiceAccount kind: ServiceAccount
metadata: metadata:
name: subchart1-sa name: subchart-sa
--- ---
# Source: subchart1/templates/subdir/role.yaml # Source: subchart/templates/subdir/role.yaml
apiVersion: rbac.authorization.k8s.io/v1 apiVersion: rbac.authorization.k8s.io/v1
kind: Role kind: Role
metadata: metadata:
name: subchart1-role name: subchart-role
rules: rules:
- resources: ["*"] - resources: ["*"]
verbs: ["get","list","watch"] verbs: ["get","list","watch"]
--- ---
# Source: subchart1/templates/subdir/rolebinding.yaml # Source: subchart/templates/subdir/rolebinding.yaml
apiVersion: rbac.authorization.k8s.io/v1 apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding kind: RoleBinding
metadata: metadata:
name: subchart1-binding name: subchart-binding
roleRef: roleRef:
apiGroup: rbac.authorization.k8s.io apiGroup: rbac.authorization.k8s.io
kind: Role kind: Role
name: subchart1-role name: subchart-role
subjects: subjects:
- kind: ServiceAccount - kind: ServiceAccount
name: subchart1-sa name: subchart-sa
namespace: default namespace: default
--- ---
# Source: subchart1/charts/subcharta/templates/service.yaml # Source: subchart/charts/subcharta/templates/service.yaml
apiVersion: v1 apiVersion: v1
kind: Service kind: Service
metadata: metadata:
@ -45,7 +45,7 @@ spec:
selector: selector:
app.kubernetes.io/name: subcharta app.kubernetes.io/name: subcharta
--- ---
# Source: subchart1/charts/subchartb/templates/service.yaml # Source: subchart/charts/subchartb/templates/service.yaml
apiVersion: v1 apiVersion: v1
kind: Service kind: Service
metadata: metadata:
@ -62,17 +62,17 @@ spec:
selector: selector:
app.kubernetes.io/name: subchartb app.kubernetes.io/name: subchartb
--- ---
# Source: subchart1/templates/service.yaml # Source: subchart/templates/service.yaml
apiVersion: v1 apiVersion: v1
kind: Service kind: Service
metadata: metadata:
name: subchart1 name: subchart
labels: labels:
helm.sh/chart: "subchart1-0.1.0" helm.sh/chart: "subchart-0.1.0"
app.kubernetes.io/instance: "RELEASE-NAME" app.kubernetes.io/instance: "RELEASE-NAME"
kube-version/major: "1" kube-version/major: "1"
kube-version/minor: "16" kube-version/minor: "18"
kube-version/version: "v1.16.0" kube-version/version: "v1.18.0"
spec: spec:
type: ClusterIP type: ClusterIP
ports: ports:
@ -81,4 +81,4 @@ spec:
protocol: TCP protocol: TCP
name: apache name: apache
selector: selector:
app.kubernetes.io/name: subchart1 app.kubernetes.io/name: subchart

@ -1,34 +1,34 @@
--- ---
# Source: subchart1/templates/subdir/serviceaccount.yaml # Source: subchart/templates/subdir/serviceaccount.yaml
apiVersion: v1 apiVersion: v1
kind: ServiceAccount kind: ServiceAccount
metadata: metadata:
name: subchart1-sa name: subchart-sa
--- ---
# Source: subchart1/templates/subdir/role.yaml # Source: subchart/templates/subdir/role.yaml
apiVersion: rbac.authorization.k8s.io/v1 apiVersion: rbac.authorization.k8s.io/v1
kind: Role kind: Role
metadata: metadata:
name: subchart1-role name: subchart-role
rules: rules:
- resources: ["*"] - resources: ["*"]
verbs: ["get","list","watch"] verbs: ["get","list","watch"]
--- ---
# Source: subchart1/templates/subdir/rolebinding.yaml # Source: subchart/templates/subdir/rolebinding.yaml
apiVersion: rbac.authorization.k8s.io/v1 apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding kind: RoleBinding
metadata: metadata:
name: subchart1-binding name: subchart-binding
roleRef: roleRef:
apiGroup: rbac.authorization.k8s.io apiGroup: rbac.authorization.k8s.io
kind: Role kind: Role
name: subchart1-role name: subchart-role
subjects: subjects:
- kind: ServiceAccount - kind: ServiceAccount
name: subchart1-sa name: subchart-sa
namespace: default namespace: default
--- ---
# Source: subchart1/charts/subcharta/templates/service.yaml # Source: subchart/charts/subcharta/templates/service.yaml
apiVersion: v1 apiVersion: v1
kind: Service kind: Service
metadata: metadata:
@ -45,7 +45,7 @@ spec:
selector: selector:
app.kubernetes.io/name: subcharta app.kubernetes.io/name: subcharta
--- ---
# Source: subchart1/charts/subchartb/templates/service.yaml # Source: subchart/charts/subchartb/templates/service.yaml
apiVersion: v1 apiVersion: v1
kind: Service kind: Service
metadata: metadata:
@ -62,17 +62,17 @@ spec:
selector: selector:
app.kubernetes.io/name: subchartb app.kubernetes.io/name: subchartb
--- ---
# Source: subchart1/templates/service.yaml # Source: subchart/templates/service.yaml
apiVersion: v1 apiVersion: v1
kind: Service kind: Service
metadata: metadata:
name: subchart1 name: subchart
labels: labels:
helm.sh/chart: "subchart1-0.1.0" helm.sh/chart: "subchart-0.1.0"
app.kubernetes.io/instance: "RELEASE-NAME" app.kubernetes.io/instance: "RELEASE-NAME"
kube-version/major: "1" kube-version/major: "1"
kube-version/minor: "16" kube-version/minor: "18"
kube-version/version: "v1.16.0" kube-version/version: "v1.18.0"
kube-api-version/test: v1 kube-api-version/test: v1
spec: spec:
type: ClusterIP type: ClusterIP
@ -82,4 +82,4 @@ spec:
protocol: TCP protocol: TCP
name: nginx name: nginx
selector: selector:
app.kubernetes.io/name: subchart1 app.kubernetes.io/name: subchart

@ -15,36 +15,36 @@ spec:
singular: authconfig singular: authconfig
--- ---
# Source: subchart1/templates/subdir/serviceaccount.yaml # Source: subchart/templates/subdir/serviceaccount.yaml
apiVersion: v1 apiVersion: v1
kind: ServiceAccount kind: ServiceAccount
metadata: metadata:
name: subchart1-sa name: subchart-sa
--- ---
# Source: subchart1/templates/subdir/role.yaml # Source: subchart/templates/subdir/role.yaml
apiVersion: rbac.authorization.k8s.io/v1 apiVersion: rbac.authorization.k8s.io/v1
kind: Role kind: Role
metadata: metadata:
name: subchart1-role name: subchart-role
rules: rules:
- resources: ["*"] - resources: ["*"]
verbs: ["get","list","watch"] verbs: ["get","list","watch"]
--- ---
# Source: subchart1/templates/subdir/rolebinding.yaml # Source: subchart/templates/subdir/rolebinding.yaml
apiVersion: rbac.authorization.k8s.io/v1 apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding kind: RoleBinding
metadata: metadata:
name: subchart1-binding name: subchart-binding
roleRef: roleRef:
apiGroup: rbac.authorization.k8s.io apiGroup: rbac.authorization.k8s.io
kind: Role kind: Role
name: subchart1-role name: subchart-role
subjects: subjects:
- kind: ServiceAccount - kind: ServiceAccount
name: subchart1-sa name: subchart-sa
namespace: default namespace: default
--- ---
# Source: subchart1/charts/subcharta/templates/service.yaml # Source: subchart/charts/subcharta/templates/service.yaml
apiVersion: v1 apiVersion: v1
kind: Service kind: Service
metadata: metadata:
@ -61,7 +61,7 @@ spec:
selector: selector:
app.kubernetes.io/name: subcharta app.kubernetes.io/name: subcharta
--- ---
# Source: subchart1/charts/subchartb/templates/service.yaml # Source: subchart/charts/subchartb/templates/service.yaml
apiVersion: v1 apiVersion: v1
kind: Service kind: Service
metadata: metadata:
@ -78,17 +78,17 @@ spec:
selector: selector:
app.kubernetes.io/name: subchartb app.kubernetes.io/name: subchartb
--- ---
# Source: subchart1/templates/service.yaml # Source: subchart/templates/service.yaml
apiVersion: v1 apiVersion: v1
kind: Service kind: Service
metadata: metadata:
name: subchart1 name: subchart
labels: labels:
helm.sh/chart: "subchart1-0.1.0" helm.sh/chart: "subchart-0.1.0"
app.kubernetes.io/instance: "RELEASE-NAME" app.kubernetes.io/instance: "RELEASE-NAME"
kube-version/major: "1" kube-version/major: "1"
kube-version/minor: "16" kube-version/minor: "18"
kube-version/version: "v1.16.0" kube-version/version: "v1.18.0"
kube-api-version/test: v1 kube-api-version/test: v1
spec: spec:
type: ClusterIP type: ClusterIP
@ -98,4 +98,4 @@ spec:
protocol: TCP protocol: TCP
name: nginx name: nginx
selector: selector:
app.kubernetes.io/name: subchart1 app.kubernetes.io/name: subchart

@ -1,34 +1,34 @@
--- ---
# Source: subchart1/templates/subdir/serviceaccount.yaml # Source: subchart/templates/subdir/serviceaccount.yaml
apiVersion: v1 apiVersion: v1
kind: ServiceAccount kind: ServiceAccount
metadata: metadata:
name: subchart1-sa name: subchart-sa
--- ---
# Source: subchart1/templates/subdir/role.yaml # Source: subchart/templates/subdir/role.yaml
apiVersion: rbac.authorization.k8s.io/v1 apiVersion: rbac.authorization.k8s.io/v1
kind: Role kind: Role
metadata: metadata:
name: subchart1-role name: subchart-role
rules: rules:
- resources: ["*"] - resources: ["*"]
verbs: ["get","list","watch"] verbs: ["get","list","watch"]
--- ---
# Source: subchart1/templates/subdir/rolebinding.yaml # Source: subchart/templates/subdir/rolebinding.yaml
apiVersion: rbac.authorization.k8s.io/v1 apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding kind: RoleBinding
metadata: metadata:
name: subchart1-binding name: subchart-binding
roleRef: roleRef:
apiGroup: rbac.authorization.k8s.io apiGroup: rbac.authorization.k8s.io
kind: Role kind: Role
name: subchart1-role name: subchart-role
subjects: subjects:
- kind: ServiceAccount - kind: ServiceAccount
name: subchart1-sa name: subchart-sa
namespace: default namespace: default
--- ---
# Source: subchart1/charts/subcharta/templates/service.yaml # Source: subchart/charts/subcharta/templates/service.yaml
apiVersion: v1 apiVersion: v1
kind: Service kind: Service
metadata: metadata:
@ -45,7 +45,7 @@ spec:
selector: selector:
app.kubernetes.io/name: subcharta app.kubernetes.io/name: subcharta
--- ---
# Source: subchart1/charts/subchartb/templates/service.yaml # Source: subchart/charts/subchartb/templates/service.yaml
apiVersion: v1 apiVersion: v1
kind: Service kind: Service
metadata: metadata:
@ -62,17 +62,17 @@ spec:
selector: selector:
app.kubernetes.io/name: subchartb app.kubernetes.io/name: subchartb
--- ---
# Source: subchart1/templates/service.yaml # Source: subchart/templates/service.yaml
apiVersion: v1 apiVersion: v1
kind: Service kind: Service
metadata: metadata:
name: subchart1 name: subchart
labels: labels:
helm.sh/chart: "subchart1-0.1.0" helm.sh/chart: "subchart-0.1.0"
app.kubernetes.io/instance: "RELEASE-NAME" app.kubernetes.io/instance: "RELEASE-NAME"
kube-version/major: "1" kube-version/major: "1"
kube-version/minor: "16" kube-version/minor: "18"
kube-version/version: "v1.16.0" kube-version/version: "v1.18.0"
spec: spec:
type: ClusterIP type: ClusterIP
ports: ports:
@ -81,4 +81,4 @@ spec:
protocol: TCP protocol: TCP
name: nginx name: nginx
selector: selector:
app.kubernetes.io/name: subchart1 app.kubernetes.io/name: subchart

@ -1 +1 @@
version.BuildInfo{Version:"v3.1", GitCommit:"", GitTreeState:"", GoVersion:""} version.BuildInfo{Version:"v3.2", GitCommit:"", GitTreeState:"", GoVersion:""}

@ -1 +1 @@
version.BuildInfo{Version:"v3.1", GitCommit:"", GitTreeState:"", GoVersion:""} version.BuildInfo{Version:"v3.2", GitCommit:"", GitTreeState:"", GoVersion:""}

@ -0,0 +1,5 @@
0.3.0-rc.1
0.2.0
0.1.0
:4
Completion ended with directive: ShellCompDirectiveNoFileComp

@ -0,0 +1,2 @@
:4
Completion ended with directive: ShellCompDirectiveNoFileComp

@ -1 +1 @@
Version: v3.1 Version: v3.2

@ -1 +1 @@
version.BuildInfo{Version:"v3.1", GitCommit:"", GitTreeState:"", GoVersion:""} version.BuildInfo{Version:"v3.2", GitCommit:"", GitTreeState:"", GoVersion:""}

@ -1 +0,0 @@
justAValue: "an example chart here"

@ -2,4 +2,22 @@
# This supports shell glob matching, relative path matching, and # This supports shell glob matching, relative path matching, and
# negation (prefixed with !). Only one pattern per line. # negation (prefixed with !). Only one pattern per line.
.DS_Store .DS_Store
.git # Common VCS dirs
.git/
.gitignore
.bzr/
.bzrignore
.hg/
.hgignore
.svn/
# Common backup files
*.swp
*.bak
*.tmp
*.orig
*~
# Various IDEs
.project
.idea/
*.tmproj
.vscode/

@ -0,0 +1,21 @@
apiVersion: v2
name: crd-test
description: A Helm chart for Kubernetes
# A chart can be either an 'application' or a 'library' chart.
#
# Application charts are a collection of templates that can be packaged into versioned archives
# to be deployed.
#
# Library charts provide useful utilities or functions for the chart developer. They're included as
# a dependency of application charts to inject those utilities and functions into the rendering
# pipeline. Library charts do not define any templates and therefore cannot be deployed.
type: application
# This is the chart version. This version number should be incremented each time you make changes
# to the chart and its templates, including the app version.
version: 0.1.0
# This is the version number of the application being deployed. This version number should be
# incremented each time you make changes to the application.
appVersion: 1.16.0

@ -0,0 +1,19 @@
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
name: tests.test.io
spec:
group: test.io
names:
kind: Test
listKind: TestList
plural: tests
singular: test
scope: Namespaced
versions:
- name : v1alpha2
served: true
storage: true
- name : v1alpha1
served: true
storage: false

@ -1,8 +0,0 @@
apiVersion: v1
description: Deploy a basic Alpine Linux pod
home: https://helm.sh/helm
name: novals
sources:
- https://github.com/helm/helm
version: 0.2.0
appVersion: 3.3

@ -1,13 +0,0 @@
#Alpine: A simple Helm chart
Run a single pod of Alpine Linux.
This example was generated using the command `helm create alpine`.
The `templates/` directory contains a very simple pod resource with a
couple of parameters.
The `values.yaml` file contains the default values for the
`alpine-pod.yaml` template.
You can install this example using `helm install ./alpine`.

@ -1,28 +0,0 @@
apiVersion: v1
kind: Pod
metadata:
name: "{{.Release.Name}}-{{.Values.Name}}"
labels:
# The "app.kubernetes.io/managed-by" label is used to track which tool
# deployed a given chart. It is useful for admins who want to see what
# releases a particular tool is responsible for.
app.kubernetes.io/managed-by: {{.Release.Service | quote }}
# The "app.kubernetes.io/instance" convention makes it easy to tie a release
# to all of the Kubernetes resources that were created as part of that
# release.
app.kubernetes.io/instance: {{.Release.Name | quote }}
app.kubernetes.io/version: {{ .Chart.AppVersion }}
# This makes it easy to audit chart usage.
helm.sh/chart: "{{.Chart.Name}}-{{.Chart.Version}}"
annotations:
"helm.sh/created": {{.Release.Time.Seconds | quote }}
spec:
# This shows how to use a simple value. This will look for a passed-in value
# called restartPolicy. If it is not found, it will use the default value.
# {{default "Never" .restartPolicy}} is a slightly optimized version of the
# more conventional syntax: {{.restartPolicy | default "Never"}}
restartPolicy: {{default "Never" .Values.restartPolicy}}
containers:
- name: waiter
image: "alpine:3.3"
command: ["/bin/sleep","9000"]

@ -0,0 +1,36 @@
apiVersion: v1
description: A Helm chart for Kubernetes
name: subchart
version: 0.1.0
dependencies:
- name: subcharta
repository: http://localhost:10191
version: 0.1.0
condition: subcharta.enabled
tags:
- front-end
- subcharta
import-values:
- child: SCAdata
parent: imported-chartA
- child: SCAdata
parent: overridden-chartA
- child: SCAdata
parent: imported-chartA-B
- name: subchartb
repository: http://localhost:10191
version: 0.1.0
condition: subchartb.enabled
import-values:
- child: SCBdata
parent: imported-chartB
- child: SCBdata
parent: imported-chartA-B
- child: exports.SCBexported2
parent: exports.SCBexported2
- SCBexported1
tags:
- front-end
- subchartb

@ -1,4 +1,4 @@
apiVersion: v1 apiVersion: v1
description: A Helm chart for Kubernetes description: A Helm chart for Kubernetes
name: spouter name: subcharta
version: 0.1.0 version: 0.1.0

@ -0,0 +1,15 @@
apiVersion: v1
kind: Service
metadata:
name: {{ .Chart.Name }}
labels:
helm.sh/chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
spec:
type: {{ .Values.service.type }}
ports:
- port: {{ .Values.service.externalPort }}
targetPort: {{ .Values.service.internalPort }}
protocol: TCP
name: {{ .Values.service.name }}
selector:
app.kubernetes.io/name: {{ .Chart.Name }}

@ -0,0 +1,17 @@
# Default values for subchart.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.
# subchartA
service:
name: apache
type: ClusterIP
externalPort: 80
internalPort: 80
SCAdata:
SCAbool: false
SCAfloat: 3.1
SCAint: 55
SCAstring: "jabba"
SCAnested1:
SCAnested2: true

@ -1,4 +1,4 @@
apiVersion: v1 apiVersion: v1
description: A Helm chart for Kubernetes description: A Helm chart for Kubernetes
name: ahab name: subchartb
version: 0.1.0 version: 0.1.0

@ -0,0 +1,15 @@
apiVersion: v1
kind: Service
metadata:
name: {{ .Chart.Name }}
labels:
helm.sh/chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
spec:
type: {{ .Values.service.type }}
ports:
- port: {{ .Values.service.externalPort }}
targetPort: {{ .Values.service.internalPort }}
protocol: TCP
name: {{ .Values.service.name }}
selector:
app.kubernetes.io/name: {{ .Chart.Name }}

@ -0,0 +1,35 @@
# Default values for subchart.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.
service:
name: nginx
type: ClusterIP
externalPort: 80
internalPort: 80
SCBdata:
SCBbool: true
SCBfloat: 7.77
SCBint: 33
SCBstring: "boba"
exports:
SCBexported1:
SCBexported1A:
SCBexported1B: 1965
SCBexported2:
SCBexported2A: "blaster"
global:
kolla:
nova:
api:
all:
port: 8774
metadata:
all:
port: 8775

@ -0,0 +1,13 @@
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
name: testCRDs
spec:
group: testCRDGroups
names:
kind: TestCRD
listKind: TestCRDList
plural: TestCRDs
shortNames:
- tc
singular: authconfig

@ -0,0 +1 @@
Sample notes for {{ .Chart.Name }}

@ -0,0 +1,22 @@
apiVersion: v1
kind: Service
metadata:
name: {{ .Chart.Name }}
labels:
helm.sh/chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
app.kubernetes.io/instance: "{{ .Release.Name }}"
kube-version/major: "{{ .Capabilities.KubeVersion.Major }}"
kube-version/minor: "{{ .Capabilities.KubeVersion.Minor }}"
kube-version/version: "v{{ .Capabilities.KubeVersion.Major }}.{{ .Capabilities.KubeVersion.Minor }}.0"
{{- if .Capabilities.APIVersions.Has "helm.k8s.io/test" }}
kube-api-version/test: v1
{{- end }}
spec:
type: {{ .Values.service.type }}
ports:
- port: {{ .Values.service.externalPort }}
targetPort: {{ .Values.service.internalPort }}
protocol: TCP
name: {{ .Values.service.name }}
selector:
app.kubernetes.io/name: {{ .Chart.Name }}

@ -0,0 +1,7 @@
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: {{ .Chart.Name }}-role
rules:
- resources: ["*"]
verbs: ["get","list","watch"]

@ -0,0 +1,12 @@
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: {{ .Chart.Name }}-binding
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: {{ .Chart.Name }}-role
subjects:
- kind: ServiceAccount
name: {{ .Chart.Name }}-sa
namespace: default

@ -0,0 +1,4 @@
apiVersion: v1
kind: ServiceAccount
metadata:
name: {{ .Chart.Name }}-sa

@ -0,0 +1,55 @@
# Default values for subchart.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.
# subchart
service:
name: nginx
type: ClusterIP
externalPort: 80
internalPort: 80
SC1data:
SC1bool: true
SC1float: 3.14
SC1int: 100
SC1string: "dollywood"
SC1extra1: 11
imported-chartA:
SC1extra2: 1.337
overridden-chartA:
SCAbool: true
SCAfloat: 3.14
SCAint: 100
SCAstring: "jabbathehut"
SC1extra3: true
imported-chartA-B:
SC1extra5: "tiller"
overridden-chartA-B:
SCAbool: true
SCAfloat: 3.33
SCAint: 555
SCAstring: "wormwood"
SCAextra1: 23
SCBbool: true
SCBfloat: 0.25
SCBint: 98
SCBstring: "murkwood"
SCBextra1: 13
SC1extra6: 77
SCBexported1A:
SC1extra7: true
exports:
SC1exported1:
global:
SC1exported2:
all:
SC1exported3: "SC1expstr"

@ -24,7 +24,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"helm.sh/helm/v3/cmd/helm/require" "helm.sh/helm/v3/cmd/helm/require"
"helm.sh/helm/v3/internal/completion"
"helm.sh/helm/v3/pkg/action" "helm.sh/helm/v3/pkg/action"
) )
@ -48,6 +47,12 @@ func newUninstallCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
Short: "uninstall a release", Short: "uninstall a release",
Long: uninstallDesc, Long: uninstallDesc,
Args: require.MinimumNArgs(1), Args: require.MinimumNArgs(1),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return compListReleases(toComplete, cfg)
},
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
for i := 0; i < len(args); i++ { for i := 0; i < len(args); i++ {
@ -65,14 +70,6 @@ func newUninstallCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
}, },
} }
// Function providing dynamic auto-completion
completion.RegisterValidArgsFunc(cmd, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) {
if len(args) != 0 {
return nil, completion.BashCompDirectiveNoFileComp
}
return compListReleases(toComplete, cfg)
})
f := cmd.Flags() f := cmd.Flags()
f.BoolVar(&client.DryRun, "dry-run", false, "simulate a uninstall") 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.DisableHooks, "no-hooks", false, "prevent hooks from running during uninstallation")

@ -19,13 +19,13 @@ package main
import ( import (
"fmt" "fmt"
"io" "io"
"log"
"time" "time"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"helm.sh/helm/v3/cmd/helm/require" "helm.sh/helm/v3/cmd/helm/require"
"helm.sh/helm/v3/internal/completion"
"helm.sh/helm/v3/pkg/action" "helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/chart/loader" "helm.sh/helm/v3/pkg/chart/loader"
"helm.sh/helm/v3/pkg/cli/output" "helm.sh/helm/v3/pkg/cli/output"
@ -72,6 +72,15 @@ func newUpgradeCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
Short: "upgrade a release", Short: "upgrade a release",
Long: upgradeDesc, Long: upgradeDesc,
Args: require.ExactArgs(2), Args: require.ExactArgs(2),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 {
return compListReleases(toComplete, cfg)
}
if len(args) == 1 {
return compListCharts(toComplete, true)
}
return nil, cobra.ShellCompDirectiveNoFileComp
},
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
client.Namespace = settings.Namespace() client.Namespace = settings.Namespace()
@ -100,6 +109,7 @@ func newUpgradeCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
instClient.PostRenderer = client.PostRenderer instClient.PostRenderer = client.PostRenderer
instClient.DisableOpenAPIValidation = client.DisableOpenAPIValidation instClient.DisableOpenAPIValidation = client.DisableOpenAPIValidation
instClient.SubNotes = client.SubNotes instClient.SubNotes = client.SubNotes
instClient.Description = client.Description
rel, err := runInstall(args, instClient, valueOpts, out) rel, err := runInstall(args, instClient, valueOpts, out)
if err != nil { if err != nil {
@ -138,7 +148,7 @@ func newUpgradeCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
} }
if ch.Metadata.Deprecated { if ch.Metadata.Deprecated {
fmt.Fprintln(out, "WARNING: This chart is deprecated") warning("This chart is deprecated")
} }
rel, err := client.Run(args[0], ch, vals) rel, err := client.Run(args[0], ch, vals)
@ -154,17 +164,6 @@ func newUpgradeCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
}, },
} }
// Function providing dynamic auto-completion
completion.RegisterValidArgsFunc(cmd, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) {
if len(args) == 0 {
return compListReleases(toComplete, cfg)
}
if len(args) == 1 {
return compListCharts(toComplete, true)
}
return nil, completion.BashCompDirectiveNoFileComp
})
f := cmd.Flags() f := cmd.Flags()
f.BoolVar(&createNamespace, "create-namespace", false, "if --install is set, create the release namespace if not present") 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.BoolVarP(&client.Install, "install", "i", false, "if a release by this name doesn't already exist, run an install")
@ -190,5 +189,16 @@ func newUpgradeCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
bindOutputFlag(cmd, &outfmt) bindOutputFlag(cmd, &outfmt)
bindPostRenderFlag(cmd, &client.PostRenderer) bindPostRenderFlag(cmd, &client.PostRenderer)
err := cmd.RegisterFlagCompletionFunc("version", func(cmd *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 return cmd
} }

@ -381,3 +381,29 @@ func prepareMockRelease(releaseName string, t *testing.T) (func(n string, v int,
func TestUpgradeOutputCompletion(t *testing.T) { func TestUpgradeOutputCompletion(t *testing.T) {
outputFlagCompletionTest(t, "upgrade") 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 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)
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save