feat(testing): enable hook parallelism

Enables parallel execution of chart hooks. --hook-parallelism defaults to 1 to make this an opt-in feature.

Batching is used to comply with "helm.sh/hook-weight" annotations. A semaphore is used to limit parallelism
to the user-provided value. Some additional synchronization was necessary to run cfg.recordRelease() in a
thread-safe manner.

Based off of https://github.com/helm/helm/pull/7792 by akhilles.

Closes #7763.

Signed-off-by: Andrew Baehre <abaehre@morningconsult.com>
pull/8946/head
abaehre 5 years ago
commit ff05abd54f
No known key found for this signature in database
GPG Key ID: 61F4AD0F4262B52F

@ -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,7 @@
version: 2
updates:
- package-ecosystem: "gomod"
directory: "/"
schedule:
interval: "daily"

@ -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

@ -0,0 +1,15 @@
name: "Close stale issues"
on:
schedule:
- cron: "0 0 * * *"
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v3
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
stale-issue-message: 'This issue has been marked as stale because it has been open for 90 days with no activity. This thread will be automatically closed in 30 days if no further activity occurs.'
exempt-issue-labels: 'keep+open,v4.x'
days-before-stale: 90
days-before-close: 30

@ -10,6 +10,7 @@
- [Microsoft](https://microsoft.com) - [Microsoft](https://microsoft.com)
- [Qovery](https://www.qovery.com/) - [Qovery](https://www.qovery.com/)
- [Samsung SDS](https://www.samsungsds.com/) - [Samsung SDS](https://www.samsungsds.com/)
- [Softonic](https://hello.softonic.com/)
- [Ville de Montreal](https://montreal.ca) - [Ville de Montreal](https://montreal.ca)
_This file is part of the CNCF official documentation for projects._ _This file is part of the CNCF official documentation for projects._

@ -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
@ -200,36 +219,38 @@ Like any good open source project, we use Pull Requests (PRs) to track code chan
- 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 - PRs from a community member with the label `size/S` or larger requires 2 review approvals from
merged. Those with `size/medium` or `size/small` are per the judgement of the maintainers. maintainers before it can be merged. Those with `size/XS` are per the judgement of the
maintainers. For more detail see the [Size Labels](#size-labels) section.
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
@ -286,22 +307,23 @@ 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 Any changes from the community labeled as `size/S` or larger should be thoroughly tested before
maintainer. This ensures there are at least two maintainers who are aware of any significant PRs merging and always requires approval from 2 core maintainers. PRs submitted by a core maintainer,
introduced to the codebase. 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 introduced to the codebase.
| Label | Description | | Label | Description |
| ----- | ----------- | | ----- | ----------- |
| `size/XS` | Denotes a PR that changes 0-9 lines, ignoring generated files. Very little testing may be required depending on the change. | | `size/XS` | Denotes a PR that changes 0-9 lines, ignoring generated files. Very little testing may be required depending on the change. |
| `size/S` | Denotes a PR that changes 10-29 lines, ignoring generated files. Only small amounts of manual testing may be required. | | `size/S` | Denotes a PR that changes 10-29 lines, ignoring generated files. Only small amounts of manual testing may be required. |
| `size/M` | Denotes a PR that changes 30-99 lines, ignoring generated files. Manual validation should be required. | | `size/M` | Denotes a PR that changes 30-99 lines, ignoring generated files. Manual validation should be required. |
| `size/L` | Denotes a PR that changes 100-499 lines, ignoring generated files. This should be thoroughly tested before merging and always requires 2 approvals. | | `size/L` | Denotes a PR that changes 100-499 lines, ignoring generated files. |
| `size/XL` | Denotes a PR that changes 500-999 lines, ignoring generated files. This should be thoroughly tested before merging and always requires 2 approvals. | | `size/XL` | Denotes a PR that changes 500-999 lines, ignoring generated files. |
| `size/XXL` | Denotes a PR that changes 1000+ lines, ignoring generated files. This should be thoroughly tested before merging and always requires 2 approvals. | | `size/XXL` | Denotes a PR that changes 1000+ lines, ignoring generated files. |

@ -1,13 +1,16 @@
BINDIR := $(CURDIR)/bin BINDIR := $(CURDIR)/bin
INSTALL_PATH ?= /usr/local/bin
DIST_DIRS := find * -type d -exec DIST_DIRS := find * -type d -exec
TARGETS := darwin/amd64 linux/amd64 linux/386 linux/arm linux/arm64 linux/ppc64le linux/s390x windows/amd64 TARGETS := darwin/amd64 linux/amd64 linux/386 linux/arm linux/arm64 linux/ppc64le linux/s390x windows/amd64
TARGET_OBJS ?= darwin-amd64.tar.gz darwin-amd64.tar.gz.sha256 darwin-amd64.tar.gz.sha256sum linux-amd64.tar.gz linux-amd64.tar.gz.sha256 linux-amd64.tar.gz.sha256sum linux-386.tar.gz linux-386.tar.gz.sha256 linux-386.tar.gz.sha256sum linux-arm.tar.gz linux-arm.tar.gz.sha256 linux-arm.tar.gz.sha256sum linux-arm64.tar.gz linux-arm64.tar.gz.sha256 linux-arm64.tar.gz.sha256sum linux-ppc64le.tar.gz linux-ppc64le.tar.gz.sha256 linux-ppc64le.tar.gz.sha256sum linux-s390x.tar.gz linux-s390x.tar.gz.sha256 linux-s390x.tar.gz.sha256sum windows-amd64.zip windows-amd64.zip.sha256 windows-amd64.zip.sha256sum TARGET_OBJS ?= darwin-amd64.tar.gz darwin-amd64.tar.gz.sha256 darwin-amd64.tar.gz.sha256sum linux-amd64.tar.gz linux-amd64.tar.gz.sha256 linux-amd64.tar.gz.sha256sum linux-386.tar.gz linux-386.tar.gz.sha256 linux-386.tar.gz.sha256sum linux-arm.tar.gz linux-arm.tar.gz.sha256 linux-arm.tar.gz.sha256sum linux-arm64.tar.gz linux-arm64.tar.gz.sha256 linux-arm64.tar.gz.sha256sum linux-ppc64le.tar.gz linux-ppc64le.tar.gz.sha256 linux-ppc64le.tar.gz.sha256sum linux-s390x.tar.gz linux-s390x.tar.gz.sha256 linux-s390x.tar.gz.sha256sum windows-amd64.zip windows-amd64.zip.sha256 windows-amd64.zip.sha256sum
BINNAME ?= helm BINNAME ?= helm
GOPATH = $(shell go env GOPATH) GOBIN = $(shell go env GOBIN)
DEP = $(GOPATH)/bin/dep ifeq ($(GOBIN),)
GOX = $(GOPATH)/bin/gox GOBIN = $(shell go env GOPATH)/bin
GOIMPORTS = $(GOPATH)/bin/goimports endif
GOX = $(GOBIN)/gox
GOIMPORTS = $(GOBIN)/goimports
ARCH = $(shell uname -p) ARCH = $(shell uname -p)
ACCEPTANCE_DIR:=../acceptance-testing ACCEPTANCE_DIR:=../acceptance-testing
@ -50,6 +53,7 @@ endif
LDFLAGS += -X helm.sh/helm/v3/internal/version.metadata=${VERSION_METADATA} LDFLAGS += -X helm.sh/helm/v3/internal/version.metadata=${VERSION_METADATA}
LDFLAGS += -X helm.sh/helm/v3/internal/version.gitCommit=${GIT_COMMIT} LDFLAGS += -X helm.sh/helm/v3/internal/version.gitCommit=${GIT_COMMIT}
LDFLAGS += -X helm.sh/helm/v3/internal/version.gitTreeState=${GIT_DIRTY} LDFLAGS += -X helm.sh/helm/v3/internal/version.gitTreeState=${GIT_DIRTY}
LDFLAGS += $(EXT_LDFLAGS)
.PHONY: all .PHONY: all
all: build all: build
@ -61,7 +65,14 @@ all: build
build: $(BINDIR)/$(BINNAME) build: $(BINDIR)/$(BINNAME)
$(BINDIR)/$(BINNAME): $(SRC) $(BINDIR)/$(BINNAME): $(SRC)
GO111MODULE=on go build $(GOFLAGS) -tags '$(TAGS)' -ldflags '$(LDFLAGS)' -o $(BINDIR)/$(BINNAME) ./cmd/helm GO111MODULE=on go build $(GOFLAGS) -tags '$(TAGS)' -ldflags '$(LDFLAGS)' -o '$(BINDIR)'/$(BINNAME) ./cmd/helm
# ------------------------------------------------------------------------------
# install
.PHONY: install
install: build
@install "$(BINDIR)/$(BINNAME)" "$(INSTALL_PATH)/$(BINNAME)"
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
# test # test
@ -98,7 +109,7 @@ test-acceptance: TARGETS = linux/amd64
test-acceptance: build build-cross test-acceptance: build build-cross
@if [ -d "${ACCEPTANCE_DIR}" ]; then \ @if [ -d "${ACCEPTANCE_DIR}" ]; then \
cd ${ACCEPTANCE_DIR} && \ cd ${ACCEPTANCE_DIR} && \
ROBOT_RUN_TESTS=$(ACCEPTANCE_RUN_TESTS) ROBOT_HELM_PATH=$(BINDIR) make acceptance; \ ROBOT_RUN_TESTS=$(ACCEPTANCE_RUN_TESTS) ROBOT_HELM_PATH='$(BINDIR)' make acceptance; \
else \ else \
echo "You must clone the acceptance_testing repo under $(ACCEPTANCE_DIR)"; \ echo "You must clone the acceptance_testing repo under $(ACCEPTANCE_DIR)"; \
echo "You can find the acceptance_testing repo at https://github.com/helm/acceptance-testing"; \ echo "You can find the acceptance_testing repo at https://github.com/helm/acceptance-testing"; \
@ -157,7 +168,7 @@ fetch-dist:
.PHONY: sign .PHONY: sign
sign: sign:
for f in _dist/*.{gz,zip,sha256,sha256sum} ; do \ for f in $$(ls _dist/*.{gz,zip,sha256,sha256sum} 2>/dev/null) ; do \
gpg --armor --detach-sign $${f} ; \ gpg --armor --detach-sign $${f} ; \
done done
@ -170,7 +181,7 @@ sign:
# removed in Helm v4. # removed in Helm v4.
.PHONY: checksum .PHONY: checksum
checksum: checksum:
for f in _dist/*.{gz,zip} ; do \ for f in $$(ls _dist/*.{gz,zip} 2>/dev/null) ; do \
shasum -a 256 "$${f}" | sed 's/_dist\///' > "$${f}.sha256sum" ; \ shasum -a 256 "$${f}" | sed 's/_dist\///' > "$${f}.sha256sum" ; \
shasum -a 256 "$${f}" | awk '{print $$1}' > "$${f}.sha256" ; \ shasum -a 256 "$${f}" | awk '{print $$1}' > "$${f}.sha256" ; \
done done
@ -179,12 +190,12 @@ checksum:
.PHONY: clean .PHONY: clean
clean: clean:
@rm -rf $(BINDIR) ./_dist @rm -rf '$(BINDIR)' ./_dist
.PHONY: release-notes .PHONY: release-notes
release-notes: release-notes:
@if [ ! -d "./_dist" ]; then \ @if [ ! -d "./_dist" ]; then \
echo "please run 'make fetch-release' first" && \ echo "please run 'make fetch-dist' first" && \
exit 1; \ exit 1; \
fi fi
@if [ -z "${PREVIOUS_RELEASE}" ]; then \ @if [ -z "${PREVIOUS_RELEASE}" ]; then \

@ -6,7 +6,6 @@ maintainers:
- jdolitsky - jdolitsky
- marckhouzam - marckhouzam
- mattfarina - mattfarina
- michelleN
- prydonius - prydonius
- SlickNik - SlickNik
- technosophos - technosophos
@ -14,6 +13,7 @@ maintainers:
- viglesiasce - viglesiasce
emeritus: emeritus:
- jascott1 - jascott1
- michelleN
- migmartri - migmartri
- nebril - nebril
- seh - seh

@ -41,8 +41,9 @@ If you want to use a package manager:
- [Chocolatey](https://chocolatey.org/) users can use `choco install kubernetes-helm`. - [Chocolatey](https://chocolatey.org/) users can use `choco install kubernetes-helm`.
- [Scoop](https://scoop.sh/) users can use `scoop install helm`. - [Scoop](https://scoop.sh/) users can use `scoop install helm`.
- [GoFish](https://gofi.sh/) users can use `gofish install helm`. - [GoFish](https://gofi.sh/) users can use `gofish install helm`.
- [Snapcraft](https://snapcraft.io/) users can use `snap install helm --classic`
To rapidly get Helm up and running, start with the [Quick Start Guide](https://docs.helm.sh/using_helm/#quickstart-guide). To rapidly get Helm up and running, start with the [Quick Start Guide](https://helm.sh/docs/intro/quickstart/).
See the [installation guide](https://helm.sh/docs/intro/install/) for more options, See the [installation guide](https://helm.sh/docs/intro/install/) for more options,
including installing pre-releases. including installing pre-releases.

@ -21,61 +21,105 @@ 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.
To load completions in your current shell session:
$ source <(helm completion bash)
This command can generate shell autocompletions. e.g. 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
`
$ helm completion bash const zshCompDesc = `
Generate the autocompletion script for Helm for the zsh shell.
Can be sourced as such To load completions in your current shell session:
$ source <(helm completion zsh)
$ source <(helm completion bash) To load completions for every new session, execute once:
$ helm completion zsh > "${fpath[1]}/_helm"
` `
var ( const fishCompDesc = `
completionShells = map[string]func(out io.Writer, cmd *cobra.Command) error{ Generate the autocompletion script for Helm for the fish shell.
"bash": runCompletionBash,
"zsh": runCompletionZsh, To load completions in your current shell session:
} $ helm completion fish | source
To load completions for every new session, execute once:
$ helm completion fish > ~/.config/fish/completions/helm.fish
You will need to start a new shell for this setup to take effect.
`
const (
noDescFlagName = "no-descriptions"
noDescFlagText = "disable completion descriptions"
) )
func newCompletionCmd(out io.Writer) *cobra.Command { var disableCompDescriptions bool
shells := []string{}
for s := range completionShells {
shells = append(shells, s)
}
func newCompletionCmd(out io.Writer) *cobra.Command {
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,
ValidArgsFunction: noCompletions, // Disable file completion
}
bash := &cobra.Command{
Use: "bash",
Short: "generate autocompletions script for bash",
Long: bashCompDesc,
Args: require.NoArgs,
DisableFlagsInUseLine: true,
ValidArgsFunction: noCompletions,
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",
Long: zshCompDesc,
Args: require.NoArgs,
DisableFlagsInUseLine: true,
ValidArgsFunction: noCompletions,
RunE: func(cmd *cobra.Command, args []string) error {
return runCompletionZsh(out, cmd)
},
} }
func runCompletion(out io.Writer, cmd *cobra.Command, args []string) error { fish := &cobra.Command{
if len(args) == 0 { Use: "fish",
return errors.New("shell not specified") Short: "generate autocompletions script for fish",
} Long: fishCompDesc,
if len(args) > 1 { Args: require.NoArgs,
return errors.New("too many arguments, expected only the shell type") DisableFlagsInUseLine: true,
} ValidArgsFunction: noCompletions,
run, found := completionShells[args[0]] RunE: func(cmd *cobra.Command, args []string) error {
if !found { return runCompletionFish(out, cmd)
return errors.Errorf("unsupported shell type %q", args[0]) },
} }
fish.Flags().BoolVar(&disableCompDescriptions, noDescFlagName, false, noDescFlagText)
cmd.AddCommand(bash, zsh, fish)
return run(out, cmd) return cmd
} }
func runCompletionBash(out io.Writer, cmd *cobra.Command) error { func runCompletionBash(out io.Writer, cmd *cobra.Command) error {
@ -139,7 +183,7 @@ __helm_compgen() {
fi fi
for w in "${completions[@]}"; do for w in "${completions[@]}"; do
if [[ "${w}" = "$1"* ]]; then if [[ "${w}" = "$1"* ]]; then
# Use printf instead of echo beause it is possible that # Use printf instead of echo because it is possible that
# the value to print is -n, which would be interpreted # the value to print is -n, which would be interpreted
# as a flag to echo # as a flag to echo
printf "%s\n" "${w}" printf "%s\n" "${w}"
@ -244,3 +288,12 @@ __helm_bash_source <(__helm_convert_bash_to_zsh)
out.Write([]byte(zshTail)) out.Write([]byte(zshTail))
return nil return nil
} }
func runCompletionFish(out io.Writer, cmd *cobra.Command) error {
return cmd.Root().GenFishCompletion(out, !disableCompDescriptions)
}
// Function to disable file completion
func noCompletions(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return nil, cobra.ShellCompDirectiveNoFileComp
}

@ -0,0 +1,59 @@
/*
Copyright The Helm Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"fmt"
"strings"
"testing"
"helm.sh/helm/v3/pkg/chart"
"helm.sh/helm/v3/pkg/release"
)
// Check if file completion should be performed according to parameter 'shouldBePerformed'
func checkFileCompletion(t *testing.T, cmdName string, shouldBePerformed bool) {
storage := storageFixture()
storage.Create(&release.Release{
Name: "myrelease",
Info: &release.Info{Status: release.StatusDeployed},
Chart: &chart.Chart{},
Version: 1,
})
testcmd := fmt.Sprintf("__complete %s ''", cmdName)
_, out, err := executeActionCommandC(storage, testcmd)
if err != nil {
t.Errorf("unexpected error, %s", err)
}
if !strings.Contains(out, "ShellCompDirectiveNoFileComp") != shouldBePerformed {
if shouldBePerformed {
t.Error(fmt.Sprintf("Unexpected directive ShellCompDirectiveNoFileComp when completing '%s'", cmdName))
} else {
t.Error(fmt.Sprintf("Did not receive directive ShellCompDirectiveNoFileComp when completing '%s'", cmdName))
}
t.Log(out)
}
}
func TestCompletionFileCompletion(t *testing.T) {
checkFileCompletion(t, "completion", false)
checkFileCompletion(t, "completion bash", false)
checkFileCompletion(t, "completion zsh", false)
checkFileCompletion(t, "completion fish", false)
}

@ -64,6 +64,15 @@ func newCreateCmd(out io.Writer) *cobra.Command {
Short: "create a new chart with the given name", Short: "create a new chart with the given name",
Long: createDesc, Long: createDesc,
Args: require.ExactArgs(1), Args: require.ExactArgs(1),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 {
// Allow file completion when completing the argument for the name
// which could be a path
return nil, cobra.ShellCompDirectiveDefault
}
// No more completions, so disable file completion
return nil, cobra.ShellCompDirectiveNoFileComp
},
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
o.name = args[0] o.name = args[0]
o.starterDir = helmpath.DataPath("starters") o.starterDir = helmpath.DataPath("starters")
@ -71,7 +80,7 @@ func newCreateCmd(out io.Writer) *cobra.Command {
}, },
} }
cmd.Flags().StringVarP(&o.starter, "starter", "p", "", "The name or absolute path to Helm starter scaffold") cmd.Flags().StringVarP(&o.starter, "starter", "p", "", "the name or absolute path to Helm starter scaffold")
return cmd return cmd
} }
@ -98,6 +107,7 @@ func (o *createOptions) run(out io.Writer) error {
return chartutil.CreateFrom(cfile, filepath.Dir(o.name), lstarter) return chartutil.CreateFrom(cfile, filepath.Dir(o.name), lstarter)
} }
chartutil.Stderr = out
_, err := chartutil.Create(chartname, filepath.Dir(o.name)) _, err := chartutil.Create(chartname, filepath.Dir(o.name))
return err return err
} }

@ -106,7 +106,7 @@ func TestCreateStarterCmd(t *testing.T) {
t.Errorf("Wrong API version: %q", c.Metadata.APIVersion) t.Errorf("Wrong API version: %q", c.Metadata.APIVersion)
} }
expectedNumberOfTemplates := 8 expectedNumberOfTemplates := 9
if l := len(c.Templates); l != expectedNumberOfTemplates { if l := len(c.Templates); l != expectedNumberOfTemplates {
t.Errorf("Expected %d templates, got %d", expectedNumberOfTemplates, l) t.Errorf("Expected %d templates, got %d", expectedNumberOfTemplates, l)
} }
@ -174,7 +174,7 @@ func TestCreateStarterAbsoluteCmd(t *testing.T) {
t.Errorf("Wrong API version: %q", c.Metadata.APIVersion) t.Errorf("Wrong API version: %q", c.Metadata.APIVersion)
} }
expectedNumberOfTemplates := 8 expectedNumberOfTemplates := 9
if l := len(c.Templates); l != expectedNumberOfTemplates { if l := len(c.Templates); l != expectedNumberOfTemplates {
t.Errorf("Expected %d templates, got %d", expectedNumberOfTemplates, l) t.Errorf("Expected %d templates, got %d", expectedNumberOfTemplates, l)
} }
@ -192,3 +192,8 @@ func TestCreateStarterAbsoluteCmd(t *testing.T) {
t.Error("Did not find foo.tpl") t.Error("Did not find foo.tpl")
} }
} }
func TestCreateFileCompletion(t *testing.T) {
checkFileCompletion(t, "create", true)
checkFileCompletion(t, "create myname", false)
}

@ -89,6 +89,7 @@ func newDependencyCmd(out io.Writer) *cobra.Command {
Short: "manage a chart's dependencies", Short: "manage a chart's dependencies",
Long: dependencyDesc, Long: dependencyDesc,
Args: require.NoArgs, Args: require.NoArgs,
ValidArgsFunction: noCompletions, // Disable file completion
} }
cmd.AddCommand(newDependencyListCmd(out)) cmd.AddCommand(newDependencyListCmd(out))

@ -16,6 +16,7 @@ limitations under the License.
package main package main
import ( import (
"fmt"
"io" "io"
"os" "os"
"path/filepath" "path/filepath"
@ -65,7 +66,11 @@ func newDependencyBuildCmd(out io.Writer) *cobra.Command {
if client.Verify { if client.Verify {
man.Verify = downloader.VerifyIfPossible man.Verify = downloader.VerifyIfPossible
} }
return man.Build() err := man.Build()
if e, ok := err.(downloader.ErrRepoNotFound); ok {
return fmt.Errorf("%s. Please add the missing repos via 'helm repo add'", e.Error())
}
return err
}, },
} }

@ -28,7 +28,7 @@ import (
) )
func TestDependencyBuildCmd(t *testing.T) { func TestDependencyBuildCmd(t *testing.T) {
srv, err := repotest.NewTempServer("testdata/testcharts/*.tgz") srv, err := repotest.NewTempServerWithCleanup(t, "testdata/testcharts/*.tgz")
defer srv.Stop() defer srv.Stop()
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)

@ -51,3 +51,7 @@ func TestDependencyListCmd(t *testing.T) {
}} }}
runTestCmd(t, tests) runTestCmd(t, tests)
} }
func TestDependencyFileCompletion(t *testing.T) {
checkFileCompletion(t, "dependency", false)
}

@ -33,7 +33,7 @@ import (
) )
func TestDependencyUpdateCmd(t *testing.T) { func TestDependencyUpdateCmd(t *testing.T) {
srv, err := repotest.NewTempServer("testdata/testcharts/*.tgz") srv, err := repotest.NewTempServerWithCleanup(t, "testdata/testcharts/*.tgz")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -121,7 +121,7 @@ func TestDependencyUpdateCmd_DontDeleteOldChartsOnError(t *testing.T) {
defer resetEnv()() defer resetEnv()()
defer ensure.HelmHome(t)() defer ensure.HelmHome(t)()
srv, err := repotest.NewTempServer("testdata/testcharts/*.tgz") srv, err := repotest.NewTempServerWithCleanup(t, "testdata/testcharts/*.tgz")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

@ -48,10 +48,11 @@ 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,
ValidArgsFunction: noCompletions,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
o.topCmd = cmd.Root() o.topCmd = cmd.Root()
return o.run(out) return o.run(out)

@ -0,0 +1,25 @@
/*
Copyright The Helm Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"testing"
)
func TestDocsFileCompletion(t *testing.T) {
checkFileCompletion(t, "docs", false)
}

@ -21,53 +21,56 @@ 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.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return o.run(out) if len(args) == 0 {
}, keys := getSortedEnvVarKeys()
return keys, cobra.ShellCompDirectiveNoFileComp
} }
return cmd return nil, cobra.ShellCompDirectiveNoFileComp
} },
Run: func(cmd *cobra.Command, args []string) {
envVars := settings.EnvVars()
if len(args) == 0 {
// Sort the variables by alphabetical order.
// This allows for a constant output across calls to 'helm env'.
keys := getSortedEnvVarKeys()
type envOptions struct { for _, k := range keys {
settings *cli.EnvSettings fmt.Fprintf(out, "%s=\"%s\"\n", k, envVars[k])
}
} else {
fmt.Fprintf(out, "%s\n", envVars[args[0]])
}
},
}
return cmd
} }
func (o *envOptions) run(out io.Writer) error { func getSortedEnvVarKeys() []string {
envVars := o.settings.EnvVars() envVars := settings.EnvVars()
// Sort the variables by alphabetical order.
// This allows for a constant output across calls to 'helm env'.
var keys []string var keys []string
for k := range envVars { for k := range envVars {
keys = append(keys, k) keys = append(keys, k)
} }
sort.Strings(keys) sort.Strings(keys)
for _, k := range keys { return keys
fmt.Printf("%s=\"%s\"\n", k, envVars[k])
}
return nil
} }

@ -0,0 +1,35 @@
/*
Copyright The Helm Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"testing"
)
func TestEnv(t *testing.T) {
tests := []cmdTestCase{{
name: "completion for env",
cmd: "__complete env ''",
golden: "output/env-comp.txt",
}}
runTestCmd(t, tests)
}
func TestEnvFileCompletion(t *testing.T) {
checkFileCompletion(t, "env", false)
checkFileCompletion(t, "env HELM_BIN", false)
}

@ -17,17 +17,22 @@ limitations under the License.
package main package main
import ( import (
"flag"
"fmt" "fmt"
"log"
"path/filepath"
"strings" "strings"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/pflag" "github.com/spf13/pflag"
"k8s.io/klog"
"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 +46,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.ShellCompDirectiveNoFileComp
}) })
if err != nil {
log.Fatal(err)
}
} }
type outputValue output.Format type outputValue output.Format
@ -124,3 +133,48 @@ 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
}
// addKlogFlags adds flags from k8s.io/klog
// marks the flags as hidden to avoid polluting the help text
func addKlogFlags(fs *pflag.FlagSet) {
local := flag.NewFlagSet("klog", flag.ExitOnError)
klog.InitFlags(local)
local.VisitAll(func(fl *flag.Flag) {
fl.Name = normalize(fl.Name)
if fs.Lookup(fl.Name) != nil {
return
}
newflag := pflag.PFlagFromGoFlag(fl)
newflag.Hidden = true
fs.AddFlag(newflag)
})
}
// normalize replaces underscores with hyphens
func normalize(s string) string {
return strings.ReplaceAll(s, "_", "-")
}

@ -41,6 +41,7 @@ func newGetCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
Short: "download extended information of a named release", Short: "download extended information of a named release",
Long: getHelp, Long: getHelp,
Args: require.NoArgs, Args: require.NoArgs,
ValidArgsFunction: noCompletions, // Disable file completion
} }
cmd.AddCommand(newGetAllCmd(cfg, out)) cmd.AddCommand(newGetAllCmd(cfg, out))

@ -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 {
@ -53,28 +59,23 @@ func newGetAllCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
return tpl(template, data, out) return tpl(template, data, out)
} }
return output.Table.Write(out, &statusPrinter{res, true}) return output.Table.Write(out, &statusPrinter{res, true, false})
}, },
} }
// 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

@ -45,3 +45,8 @@ func TestGetCmd(t *testing.T) {
func TestGetAllRevisionCompletion(t *testing.T) { func TestGetAllRevisionCompletion(t *testing.T) {
revisionFlagCompletionTest(t, "get all") revisionFlagCompletionTest(t, "get all")
} }
func TestGetAllFileCompletion(t *testing.T) {
checkFileCompletion(t, "get all", false)
checkFileCompletion(t, "get all myrelease", false)
}

@ -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 { if len(args) == 1 {
return nil, completion.BashCompDirectiveNoFileComp return compListRevisions(toComplete, cfg, args[0])
} }
return compListReleases(toComplete, cfg) return nil, cobra.ShellCompDirectiveNoFileComp
}) })
f := cmd.Flags() if err != nil {
f.IntVar(&client.Version, "revision", 0, "get the named release with revision") log.Fatal(err)
flag := f.Lookup("revision")
completion.RegisterFlagCompletionFunc(flag, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) {
if len(args) == 1 {
return compListRevisions(cfg, args[0])
} }
return nil, completion.BashCompDirectiveNoFileComp
})
return cmd return cmd
} }

@ -40,3 +40,8 @@ func TestGetHooks(t *testing.T) {
func TestGetHooksRevisionCompletion(t *testing.T) { func TestGetHooksRevisionCompletion(t *testing.T) {
revisionFlagCompletionTest(t, "get hooks") revisionFlagCompletionTest(t, "get hooks")
} }
func TestGetHooksFileCompletion(t *testing.T) {
checkFileCompletion(t, "get hooks", false)
checkFileCompletion(t, "get hooks myrelease", false)
}

@ -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 { if len(args) == 1 {
return nil, completion.BashCompDirectiveNoFileComp return compListRevisions(toComplete, cfg, args[0])
} }
return compListReleases(toComplete, cfg) return nil, cobra.ShellCompDirectiveNoFileComp
}) })
f := cmd.Flags() if err != nil {
f.IntVar(&client.Version, "revision", 0, "get the named release with revision") log.Fatal(err)
flag := f.Lookup("revision")
completion.RegisterFlagCompletionFunc(flag, func(cmd *cobra.Command, args []string, toComplete string) ([]string, completion.BashCompDirective) {
if len(args) == 1 {
return compListRevisions(cfg, args[0])
} }
return nil, completion.BashCompDirectiveNoFileComp
})
return cmd return cmd
} }

@ -40,3 +40,8 @@ func TestGetManifest(t *testing.T) {
func TestGetManifestRevisionCompletion(t *testing.T) { func TestGetManifestRevisionCompletion(t *testing.T) {
revisionFlagCompletionTest(t, "get manifest") revisionFlagCompletionTest(t, "get manifest")
} }
func TestGetManifestFileCompletion(t *testing.T) {
checkFileCompletion(t, "get manifest", false)
checkFileCompletion(t, "get manifest myrelease", false)
}

@ -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
} }

@ -40,3 +40,8 @@ func TestGetNotesCmd(t *testing.T) {
func TestGetNotesRevisionCompletion(t *testing.T) { func TestGetNotesRevisionCompletion(t *testing.T) {
revisionFlagCompletionTest(t, "get notes") revisionFlagCompletionTest(t, "get notes")
} }
func TestGetNotesFileCompletion(t *testing.T) {
checkFileCompletion(t, "get notes", false)
checkFileCompletion(t, "get notes myrelease", false)
}

@ -0,0 +1,25 @@
/*
Copyright The Helm Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"testing"
)
func TestGetFileCompletion(t *testing.T) {
checkFileCompletion(t, "get", false)
}

@ -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)

@ -60,3 +60,8 @@ func TestGetValuesRevisionCompletion(t *testing.T) {
func TestGetValuesOutputCompletion(t *testing.T) { func TestGetValuesOutputCompletion(t *testing.T) {
outputFlagCompletionTest(t, "get values") outputFlagCompletionTest(t, "get values")
} }
func TestGetValuesFileCompletion(t *testing.T) {
checkFileCompletion(t, "get values", false)
checkFileCompletion(t, "get values myrelease", false)
}

@ -17,7 +17,6 @@ limitations under the License.
package main // import "helm.sh/helm/v3/cmd/helm" package main // import "helm.sh/helm/v3/cmd/helm"
import ( import (
"flag"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"log" "log"
@ -25,14 +24,11 @@ import (
"strings" "strings"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/pflag"
"k8s.io/klog"
"sigs.k8s.io/yaml" "sigs.k8s.io/yaml"
// Import to initialize client auth plugins. // Import to initialize client auth plugins.
_ "k8s.io/client-go/plugin/pkg/client/auth" _ "k8s.io/client-go/plugin/pkg/client/auth"
"helm.sh/helm/v3/internal/completion"
"helm.sh/helm/v3/pkg/action" "helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/cli" "helm.sh/helm/v3/pkg/cli"
"helm.sh/helm/v3/pkg/gates" "helm.sh/helm/v3/pkg/gates"
@ -44,9 +40,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)
@ -59,30 +53,21 @@ func debug(format string, v ...interface{}) {
} }
} }
func initKubeLogs() { func warning(format string, v ...interface{}) {
pflag.CommandLine.SetNormalizeFunc(wordSepNormalizeFunc) format = fmt.Sprintf("WARNING: %s\n", format)
gofs := flag.NewFlagSet("klog", flag.ExitOnError) fmt.Fprintf(os.Stderr, format, v...)
klog.InitFlags(gofs)
pflag.CommandLine.AddGoFlagSet(gofs)
pflag.CommandLine.Set("logtostderr", "true")
} }
func main() { func main() {
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 {
if calledCmd, _, err := cmd.Find(os.Args[1:]); err == nil && calledCmd.Name() == completion.CompRequestCmd { debug("%+v", err)
// If completion is being called, we have to check if the completion is for the "--kube-context" os.Exit(1)
// value; if it is, we cannot call the action.Init() method with an incomplete kube-context value
// or else it will fail immediately. So, we simply unset the invalid kube-context value.
if args := os.Args[1:]; len(args) > 2 && args[len(args)-2] == "--kube-context" {
// We are completing the kube-context value! Reset it as the current value is not valid.
settings.KubeContext = ""
}
} }
// run when each command's execute method is called
cobra.OnInitialize(func() {
helmDriver := os.Getenv("HELM_DRIVER") helmDriver := os.Getenv("HELM_DRIVER")
if err := actionConfig.Init(settings.RESTClientGetter(), settings.Namespace(), helmDriver, debug); err != nil { if err := actionConfig.Init(settings.RESTClientGetter(), settings.Namespace(), helmDriver, debug); err != nil {
log.Fatal(err) log.Fatal(err)
@ -90,6 +75,7 @@ func main() {
if helmDriver == "memory" { if helmDriver == "memory" {
loadReleasesInMemory(actionConfig) loadReleasesInMemory(actionConfig)
} }
})
if err := cmd.Execute(); err != nil { if err := cmd.Execute(); err != nil {
debug("%+v", err) debug("%+v", err)
@ -102,11 +88,6 @@ func main() {
} }
} }
// wordSepNormalizeFunc changes all flags that contain "_" separators
func wordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {
return pflag.NormalizedName(strings.ReplaceAll(name, "_", "-"))
}
func checkOCIFeatureGate() func(_ *cobra.Command, _ []string) error { func checkOCIFeatureGate() func(_ *cobra.Command, _ []string) error {
return func(_ *cobra.Command, _ []string) error { return func(_ *cobra.Command, _ []string) error {
if !FeatureGateOCI.IsEnabled() { if !FeatureGateOCI.IsEnabled() {

@ -97,10 +97,15 @@ func storageFixture() *storage.Storage {
} }
func executeActionCommandC(store *storage.Storage, cmd string) (*cobra.Command, string, error) { func executeActionCommandC(store *storage.Storage, cmd string) (*cobra.Command, string, error) {
return executeActionCommandStdinC(store, nil, cmd)
}
func executeActionCommandStdinC(store *storage.Storage, in *os.File, cmd string) (*cobra.Command, string, error) {
args, err := shellwords.Parse(cmd) args, err := shellwords.Parse(cmd)
if err != nil { if err != nil {
return nil, "", err return nil, "", err
} }
buf := new(bytes.Buffer) buf := new(bytes.Buffer)
actionConfig := &action.Configuration{ actionConfig := &action.Configuration{
@ -110,16 +115,31 @@ func executeActionCommandC(store *storage.Storage, cmd string) (*cobra.Command,
Log: func(format string, v ...interface{}) {}, Log: func(format string, v ...interface{}) {},
} }
root := newRootCmd(actionConfig, buf, args) root, err := newRootCmd(actionConfig, buf, args)
root.SetOutput(buf) if err != nil {
return nil, "", err
}
root.SetOut(buf)
root.SetErr(buf)
root.SetArgs(args) root.SetArgs(args)
oldStdin := os.Stdin
if in != nil {
root.SetIn(in)
os.Stdin = in
}
if mem, ok := store.Driver.(*driver.Memory); ok { if mem, ok := store.Driver.(*driver.Memory); ok {
mem.SetNamespace(settings.Namespace()) mem.SetNamespace(settings.Namespace())
} }
c, err := root.ExecuteC() c, err := root.ExecuteC()
return c, buf.String(), err result := buf.String()
os.Stdin = oldStdin
return c, result, err
} }
// cmdTestCase describes a test case that works with releases. // cmdTestCase describes a test case that works with releases.

@ -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
} }

@ -108,3 +108,8 @@ func revisionFlagCompletionTest(t *testing.T, cmdName string) {
}} }}
runTestCmd(t, tests) runTestCmd(t, tests)
} }
func TestHistoryFileCompletion(t *testing.T) {
checkFileCompletion(t, "history", false)
checkFileCompletion(t, "history myrelease", false)
}

@ -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,29 +113,27 @@ 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 {
return err return err
} }
return outfmt.Write(out, &statusPrinter{rel, settings.Debug}) return outfmt.Write(out, &statusPrinter{rel, settings.Debug, false})
}, },
} }
// 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")
@ -149,11 +147,26 @@ func addInstallFlags(f *pflag.FlagSet, client *action.Install, valueOpts *values
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.DependencyUpdate, "dependency-update", false, "run helm dependency update before installing the chart") f.BoolVar(&client.DependencyUpdate, "dependency-update", false, "run helm dependency update before installing the chart")
f.BoolVar(&client.DisableOpenAPIValidation, "disable-openapi-validation", false, "if set, the installation process will not validate rendered templates against the Kubernetes OpenAPI Schema") f.BoolVar(&client.DisableOpenAPIValidation, "disable-openapi-validation", false, "if set, the installation process will not validate rendered templates against the Kubernetes OpenAPI Schema")
f.BoolVar(&client.Atomic, "atomic", false, "if set, installation process purges chart on fail. The --wait flag will be set automatically if --atomic is used") f.BoolVar(&client.Atomic, "atomic", false, "if set, the installation process deletes the installation on failure. The --wait flag will be set automatically if --atomic is used")
f.BoolVar(&client.SkipCRDs, "skip-crds", false, "if set, no CRDs will be installed. By default, CRDs are installed if not already present") f.BoolVar(&client.SkipCRDs, "skip-crds", false, "if set, no CRDs will be installed. By default, CRDs are installed if not already present")
f.BoolVar(&client.SubNotes, "render-subchart-notes", false, "if set, render subchart notes along with the parent") f.BoolVar(&client.SubNotes, "render-subchart-notes", false, "if set, render subchart notes along with the parent")
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) {
@ -188,13 +201,12 @@ func runInstall(args []string, client *action.Install, valueOpts *values.Options
return nil, err return nil, err
} }
validInstallableChart, err := isChartInstallable(chartRequested) if err := checkIfInstallable(chartRequested); err != nil {
if !validInstallableChart {
return nil, err return nil, err
} }
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 {
@ -211,10 +223,15 @@ func runInstall(args []string, client *action.Install, valueOpts *values.Options
Getters: p, Getters: p,
RepositoryConfig: settings.RepositoryConfig, RepositoryConfig: settings.RepositoryConfig,
RepositoryCache: settings.RepositoryCache, RepositoryCache: settings.RepositoryCache,
Debug: settings.Debug,
} }
if err := man.Update(); err != nil { if err := man.Update(); err != nil {
return nil, err return nil, err
} }
// Reload the chart with the updated Chart.lock file.
if chartRequested, err = loader.Load(cp); err != nil {
return nil, errors.Wrap(err, "failed reloading chart after repo update")
}
} else { } else {
return nil, err return nil, err
} }
@ -225,19 +242,19 @@ func runInstall(args []string, client *action.Install, valueOpts *values.Options
return client.Run(chartRequested, vals) return client.Run(chartRequested, vals)
} }
// isChartInstallable validates if a chart can be installed // checkIfInstallable validates if a chart can be installed
// //
// Application chart type is only installable // Application chart type is only installable
func isChartInstallable(ch *chart.Chart) (bool, error) { func checkIfInstallable(ch *chart.Chart) error {
switch ch.Metadata.Type { switch ch.Metadata.Type {
case "", "application": case "", "application":
return true, nil return nil
} }
return false, errors.Errorf("%s charts are not installable", ch.Metadata.Type) return errors.Errorf("%s charts are not installable", ch.Metadata.Type)
} }
// 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
@ -245,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"
) )
@ -111,6 +112,12 @@ func TestInstall(t *testing.T) {
cmd: "install nodeps testdata/testcharts/chart-missing-deps", cmd: "install nodeps testdata/testcharts/chart-missing-deps",
wantError: true, wantError: true,
}, },
// Install chart with update-dependency
{
name: "install chart with missing dependencies",
cmd: "install --dependency-update updeps testdata/testcharts/chart-with-subchart-update",
golden: "output/chart-with-subchart-update.txt",
},
// Install, chart with bad dependencies in Chart.yaml in /charts // Install, chart with bad dependencies in Chart.yaml in /charts
{ {
name: "install chart with bad dependencies in Chart.yaml", name: "install chart with bad dependencies in Chart.yaml",
@ -189,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)
@ -197,3 +209,40 @@ 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)
}
func TestInstallFileCompletion(t *testing.T) {
checkFileCompletion(t, "install", false)
checkFileCompletion(t, "install --generate-name", true)
checkFileCompletion(t, "install myname", true)
checkFileCompletion(t, "install myname mychart", false)
}

@ -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{"."}

@ -27,7 +27,7 @@ func TestLintCmdWithSubchartsFlag(t *testing.T) {
name: "lint good chart with bad subcharts", name: "lint good chart with bad subcharts",
cmd: fmt.Sprintf("lint %s", testChart), cmd: fmt.Sprintf("lint %s", testChart),
golden: "output/lint-chart-with-bad-subcharts.txt", golden: "output/lint-chart-with-bad-subcharts.txt",
wantError: false, wantError: true,
}, { }, {
name: "lint good chart with bad subcharts using --with-subcharts flag", name: "lint good chart with bad subcharts using --with-subcharts flag",
cmd: fmt.Sprintf("lint --with-subcharts %s", testChart), cmd: fmt.Sprintf("lint --with-subcharts %s", testChart),
@ -36,3 +36,8 @@ func TestLintCmdWithSubchartsFlag(t *testing.T) {
}} }}
runTestCmd(t, tests) runTestCmd(t, tests)
} }
func TestLintFileCompletion(t *testing.T) {
checkFileCompletion(t, "lint", true)
checkFileCompletion(t, "lint mypath", true) // Multiple paths can be given
}

@ -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"
@ -69,6 +68,7 @@ func newListCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
Long: listHelp, Long: listHelp,
Aliases: []string{"ls"}, Aliases: []string{"ls"},
Args: require.NoArgs, Args: require.NoArgs,
ValidArgsFunction: noCompletions,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
if client.AllNamespaces { if client.AllNamespaces {
if err := cfg.Init(settings.RESTClientGetter(), "", os.Getenv("HELM_DRIVER"), debug); err != nil { if err := cfg.Init(settings.RESTClientGetter(), "", os.Getenv("HELM_DRIVER"), debug); err != nil {
@ -83,10 +83,29 @@ func newListCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
} }
if client.Short { if client.Short {
names := make([]string, 0)
for _, res := range results {
names = append(names, res.Name)
}
outputFlag := cmd.Flag("output")
switch outputFlag.Value.String() {
case "json":
output.EncodeJSON(out, names)
return nil
case "yaml":
output.EncodeYAML(out, names)
return nil
case "table":
for _, res := range results { for _, res := range results {
fmt.Fprintln(out, res.Name) fmt.Fprintln(out, res.Name)
} }
return nil return nil
default:
return outfmt.Write(out, newReleaseListWriter(results))
}
} }
return outfmt.Write(out, newReleaseListWriter(results)) return outfmt.Write(out, newReleaseListWriter(results))
@ -108,6 +127,7 @@ func newListCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
f.IntVarP(&client.Limit, "max", "m", 256, "maximum number of releases to fetch") f.IntVarP(&client.Limit, "max", "m", 256, "maximum number of releases to fetch")
f.IntVar(&client.Offset, "offset", 0, "next release name in the list, used to offset from start value") f.IntVar(&client.Offset, "offset", 0, "next release name in the list, used to offset from start value")
f.StringVarP(&client.Filter, "filter", "f", "", "a regular expression (Perl compatible). Any releases that match the expression will be included in the results") f.StringVarP(&client.Filter, "filter", "f", "", "a regular expression (Perl compatible). Any releases that match the expression will be included in the results")
f.StringVarP(&client.Selector, "selector", "l", "", "Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Works only for secret(default) and configmap storage backends.")
bindOutputFlag(cmd, &outfmt) bindOutputFlag(cmd, &outfmt)
return cmd return cmd
@ -167,8 +187,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
@ -178,7 +198,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
@ -186,5 +206,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
} }

@ -198,6 +198,16 @@ func TestListCmd(t *testing.T) {
cmd: "list --short", cmd: "list --short",
golden: "output/list-short.txt", golden: "output/list-short.txt",
rels: releaseFixture, rels: releaseFixture,
}, {
name: "list releases in short output format",
cmd: "list --short --output yaml",
golden: "output/list-short-yaml.txt",
rels: releaseFixture,
}, {
name: "list releases in short output format",
cmd: "list --short --output json",
golden: "output/list-short-json.txt",
rels: releaseFixture,
}, { }, {
name: "list superseded releases", name: "list superseded releases",
cmd: "list --superseded", cmd: "list --superseded",
@ -225,3 +235,7 @@ func TestListCmd(t *testing.T) {
func TestListOutputCompletion(t *testing.T) { func TestListOutputCompletion(t *testing.T) {
outputFlagCompletionTest(t, "list") outputFlagCompletionTest(t, "list")
} }
func TestListFileCompletion(t *testing.T) {
checkFileCompletion(t, "list", false)
}

@ -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"
) )
@ -58,24 +57,9 @@ func loadPlugins(baseCmd *cobra.Command, out io.Writer) {
return return
} }
found, err := findPlugins(settings.PluginsDirectory) found, err := plugin.FindPlugins(settings.PluginsDirectory)
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "failed to load plugins: %s", err) fmt.Fprintf(os.Stderr, "failed to load plugins: %s\n", err)
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 return
} }
@ -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:])
if (err == nil &&
((subCmd.HasParent() && subCmd.Parent().Name() == "completion") || subCmd.Name() == cobra.ShellCompRequestCmd)) ||
/* for the tests */ subCmd == baseCmd.Root() {
loadCompletionForPlugin(c, plug)
}
} }
plugin.SetupPluginEnv(settings, md.Name, plug.Dir)
completion.CompDebugln(fmt.Sprintf("calling %s with args %v", main, argv))
buf := new(bytes.Buffer)
if err := callPluginExecutable(cmd, main, argv, buf); err != nil {
return nil, completion.BashCompDirectiveError
} }
var completions []string func processParent(cmd *cobra.Command, args []string) ([]string, error) {
for _, comp := range strings.Split(buf.String(), "\n") { k, u := manuallyProcessArgs(args)
// Remove any empty lines if err := cmd.Parent().ParseFlags(k); err != nil {
if len(comp) > 0 { return nil, err
completions = append(completions, comp)
} }
return u, nil
} }
// Check if the last line of output is of the form :<integer>, which // This function is used to setup the environment for the plugin and then
// indicates the BashCompletionDirective. // call the executable specified by the parameter 'main'
directive := completion.BashCompDirectiveDefault func callPluginExecutable(pluginName string, main string, argv []string, out io.Writer) error {
if len(completions) > 0 { env := os.Environ()
lastLine := completions[len(completions)-1] for k, v := range settings.EnvVars() {
if len(lastLine) > 1 && lastLine[0] == ':' { env = append(env, fmt.Sprintf("%s=%s", k, v))
if strInt, err := strconv.Atoi(lastLine[1:]); err == nil {
directive = completion.BashCompDirective(strInt)
completions = completions[:len(completions)-1]
} }
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", pluginName),
code: status.ExitStatus(),
} }
} }
return err
return completions, directive
})
// 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.
@ -198,7 +154,7 @@ func loadPlugins(baseCmd *cobra.Command, out io.Writer) {
func manuallyProcessArgs(args []string) ([]string, []string) { func manuallyProcessArgs(args []string) ([]string, []string) {
known := []string{} known := []string{}
unknown := []string{} unknown := []string{}
kvargs := []string{"--kube-context", "--namespace", "-n", "--kubeconfig", "--kube-apiserver", "--kube-token", "--registry-config", "--repository-cache", "--repository-config"} kvargs := []string{"--kube-context", "--namespace", "-n", "--kubeconfig", "--kube-apiserver", "--kube-token", "--kube-as-user", "--kube-as-group", "--registry-config", "--repository-cache", "--repository-config"}
knownArg := func(a string) bool { knownArg := func(a string) bool {
for _, pre := range kvargs { for _, pre := range kvargs {
if strings.HasPrefix(a, pre+"=") { if strings.HasPrefix(a, pre+"=") {
@ -238,20 +194,6 @@ func manuallyProcessArgs(args []string) ([]string, []string) {
return known, unknown return known, unknown
} }
// findPlugins returns a list of YAML files that describe plugins.
func findPlugins(plugdirs string) ([]*plugin.Plugin, error) {
found := []*plugin.Plugin{}
// Let's get all UNIXy and allow path separators
for _, p := range filepath.SplitList(plugdirs) {
matches, err := plugin.LoadAll(p)
if err != nil {
return matches, err
}
found = append(found, matches...)
}
return found, nil
}
// pluginCommand represents the optional completion.yaml file of a plugin // pluginCommand represents the optional completion.yaml file of a plugin
type pluginCommand struct { type pluginCommand struct {
Name string `json:"name"` Name string `json:"name"`
@ -260,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
} }
@ -301,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 {
@ -328,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) {
@ -352,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)
} }
} }
@ -367,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
}

@ -114,6 +114,7 @@ func newPackageCmd(out io.Writer) *cobra.Command {
f.BoolVar(&client.Sign, "sign", false, "use a PGP private key to sign this package") f.BoolVar(&client.Sign, "sign", false, "use a PGP private key to sign this package")
f.StringVar(&client.Key, "key", "", "name of the key to use when signing. Used if --sign is true") f.StringVar(&client.Key, "key", "", "name of the key to use when signing. Used if --sign is true")
f.StringVar(&client.Keyring, "keyring", defaultKeyring(), "location of a public keyring") f.StringVar(&client.Keyring, "keyring", defaultKeyring(), "location of a public keyring")
f.StringVar(&client.PassphraseFile, "passphrase-file", "", `location of a file which contains the passphrase for the signing key. Use "-" in order to read from stdin.`)
f.StringVar(&client.Version, "version", "", "set the version on the chart to this semver version") f.StringVar(&client.Version, "version", "", "set the version on the chart to this semver version")
f.StringVar(&client.AppVersion, "app-version", "", "set the appVersion on the chart to this version") f.StringVar(&client.AppVersion, "app-version", "", "set the appVersion on the chart to this version")
f.StringVarP(&client.Destination, "destination", "d", ".", "location to write the chart.") f.StringVarP(&client.Destination, "destination", "d", ".", "location to write the chart.")

@ -202,3 +202,8 @@ func setFlags(cmd *cobra.Command, flags map[string]string) {
dest.Set(f, v) dest.Set(f, v)
} }
} }
func TestPackageFileCompletion(t *testing.T) {
checkFileCompletion(t, "package", true)
checkFileCompletion(t, "package mypath", true) // Multiple paths can be given
}

@ -35,6 +35,7 @@ func newPluginCmd(out io.Writer) *cobra.Command {
Use: "plugin", Use: "plugin",
Short: "install, list, or uninstall Helm plugins", Short: "install, list, or uninstall Helm plugins",
Long: pluginHelp, Long: pluginHelp,
ValidArgsFunction: noCompletions, // Disable file completion
} }
cmd.AddCommand( cmd.AddCommand(
newPluginInstallCmd(out), newPluginInstallCmd(out),

@ -19,6 +19,7 @@ import (
"fmt" "fmt"
"io" "io"
"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"
@ -43,6 +44,14 @@ func newPluginInstallCmd(out io.Writer) *cobra.Command {
Long: pluginInstallDesc, Long: pluginInstallDesc,
Aliases: []string{"add"}, Aliases: []string{"add"},
Args: require.ExactArgs(1), Args: require.ExactArgs(1),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 {
// We do file completion, in case the plugin is local
return nil, cobra.ShellCompDirectiveDefault
}
// No more completion once the plugin path has been specified
return nil, 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)
}, },
@ -73,7 +82,7 @@ func (o *pluginInstallOptions) run(out io.Writer) error {
debug("loading plugin from %s", i.Path()) debug("loading plugin from %s", i.Path())
p, err := plugin.LoadDir(i.Path()) p, err := plugin.LoadDir(i.Path())
if err != nil { if err != nil {
return err return errors.Wrap(err, "plugin is installed but unusable")
} }
if err := runHook(p, plugin.Install); err != nil { if err := runHook(p, plugin.Install); err != nil {

@ -22,6 +22,8 @@ import (
"github.com/gosuri/uitable" "github.com/gosuri/uitable"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"helm.sh/helm/v3/pkg/plugin"
) )
func newPluginListCmd(out io.Writer) *cobra.Command { func newPluginListCmd(out io.Writer) *cobra.Command {
@ -29,9 +31,10 @@ func newPluginListCmd(out io.Writer) *cobra.Command {
Use: "list", Use: "list",
Aliases: []string{"ls"}, Aliases: []string{"ls"},
Short: "list installed Helm plugins", Short: "list installed Helm plugins",
ValidArgsFunction: noCompletions,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
debug("pluginDirs: %s", settings.PluginsDirectory) debug("pluginDirs: %s", settings.PluginsDirectory)
plugins, err := findPlugins(settings.PluginsDirectory) plugins, err := plugin.FindPlugins(settings.PluginsDirectory)
if err != nil { if err != nil {
return err return err
} }
@ -51,7 +54,7 @@ func newPluginListCmd(out io.Writer) *cobra.Command {
// Provide dynamic auto-completion for plugin names // Provide dynamic auto-completion for plugin names
func compListPlugins(toComplete string) []string { func compListPlugins(toComplete string) []string {
var pNames []string var pNames []string
plugins, err := findPlugins(settings.PluginsDirectory) plugins, err := plugin.FindPlugins(settings.PluginsDirectory)
if err == nil { if err == nil {
for _, p := range plugins { for _, p := range plugins {
if strings.HasPrefix(p.Metadata.Name, toComplete) { if strings.HasPrefix(p.Metadata.Name, toComplete) {

@ -37,6 +37,9 @@ func TestManuallyProcessArgs(t *testing.T) {
"--kubeconfig", "/home/foo", "--kubeconfig", "/home/foo",
"--kube-context=test1", "--kube-context=test1",
"--kube-context", "test1", "--kube-context", "test1",
"--kube-as-user", "pikachu",
"--kube-as-group", "teatime",
"--kube-as-group", "admins",
"-n=test2", "-n=test2",
"-n", "test2", "-n", "test2",
"--namespace=test2", "--namespace=test2",
@ -51,6 +54,9 @@ func TestManuallyProcessArgs(t *testing.T) {
"--kubeconfig", "/home/foo", "--kubeconfig", "/home/foo",
"--kube-context=test1", "--kube-context=test1",
"--kube-context", "test1", "--kube-context", "test1",
"--kube-as-user", "pikachu",
"--kube-as-group", "teatime",
"--kube-as-group", "admins",
"-n=test2", "-n=test2",
"-n", "test2", "-n", "test2",
"--namespace=test2", "--namespace=test2",
@ -298,3 +304,26 @@ func TestLoadPlugins_HelmNoPlugins(t *testing.T) {
t.Fatalf("Expected 0 plugins, got %d", len(plugins)) t.Fatalf("Expected 0 plugins, got %d", len(plugins))
} }
} }
func TestPluginFileCompletion(t *testing.T) {
checkFileCompletion(t, "plugin", false)
}
func TestPluginInstallFileCompletion(t *testing.T) {
checkFileCompletion(t, "plugin install", true)
checkFileCompletion(t, "plugin install mypath", false)
}
func TestPluginListFileCompletion(t *testing.T) {
checkFileCompletion(t, "plugin list", false)
}
func TestPluginUninstallFileCompletion(t *testing.T) {
checkFileCompletion(t, "plugin uninstall", false)
checkFileCompletion(t, "plugin uninstall myplugin", false)
}
func TestPluginUpdateFileCompletion(t *testing.T) {
checkFileCompletion(t, "plugin update", false)
checkFileCompletion(t, "plugin update myplugin", false)
}

@ -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
} }
@ -68,7 +64,7 @@ func (o *pluginUninstallOptions) complete(args []string) error {
func (o *pluginUninstallOptions) run(out io.Writer) error { func (o *pluginUninstallOptions) run(out io.Writer) error {
debug("loading installed plugins from %s", settings.PluginsDirectory) debug("loading installed plugins from %s", settings.PluginsDirectory)
plugins, err := findPlugins(settings.PluginsDirectory) plugins, err := plugin.FindPlugins(settings.PluginsDirectory)
if err != nil { if err != nil {
return err return err
} }

@ -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
} }
@ -70,7 +66,7 @@ func (o *pluginUpdateOptions) complete(args []string) error {
func (o *pluginUpdateOptions) run(out io.Writer) error { func (o *pluginUpdateOptions) run(out io.Writer) error {
installer.Debug = settings.Debug installer.Debug = settings.Debug
debug("loading installed plugins from %s", settings.PluginsDirectory) debug("loading installed plugins from %s", settings.PluginsDirectory)
plugins, err := findPlugins(settings.PluginsDirectory) plugins, err := plugin.FindPlugins(settings.PluginsDirectory)
if err != nil { if err != nil {
return err return err
} }

@ -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
} }

@ -26,7 +26,7 @@ import (
) )
func TestPullCmd(t *testing.T) { func TestPullCmd(t *testing.T) {
srv, err := repotest.NewTempServer("testdata/testcharts/*.tgz*") srv, err := repotest.NewTempServerWithCleanup(t, "testdata/testcharts/*.tgz*")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -195,3 +195,34 @@ 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)
}
func TestPullFileCompletion(t *testing.T) {
checkFileCompletion(t, "pull", false)
checkFileCompletion(t, "pull repo/chart", false)
}

@ -104,7 +104,7 @@ func getUsernamePassword(usernameOpt string, passwordOpt string, passwordFromStd
} }
} }
} else { } else {
fmt.Fprintln(os.Stderr, "WARNING! Using --password via the CLI is insecure. Use --password-stdin.") warning("Using --password via the CLI is insecure. Use --password-stdin.")
} }
return username, password, nil return username, password, nil

@ -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])
@ -56,7 +61,7 @@ func newReleaseTestCmd(cfg *action.Configuration, out io.Writer) *cobra.Command
return runErr return runErr
} }
if err := outfmt.Write(out, &statusPrinter{rel, settings.Debug}); err != nil { if err := outfmt.Write(out, &statusPrinter{rel, settings.Debug, false}); err != nil {
return err return err
} }
@ -72,18 +77,10 @@ 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.IntVar(&client.HookParallelism, "hook-parallelism", 1, "maximum number of hooks to execute in parallel") f.IntVar(&client.HookParallelism, "hook-parallelism", 1, "maximum number of hooks to execute in parallel")
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)")
return cmd return cmd
} }

@ -0,0 +1,26 @@
/*
Copyright The Helm Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"testing"
)
func TestReleaseTestingFileCompletion(t *testing.T) {
checkFileCompletion(t, "test", false)
checkFileCompletion(t, "test myrelease", false)
}

@ -38,6 +38,7 @@ func newRepoCmd(out io.Writer) *cobra.Command {
Short: "add, list, remove, update, and index chart repositories", Short: "add, list, remove, update, and index chart repositories",
Long: repoHelm, Long: repoHelm,
Args: require.NoArgs, Args: require.NoArgs,
ValidArgsFunction: noCompletions, // Disable file completion
} }
cmd.AddCommand(newRepoAddCmd(out)) cmd.AddCommand(newRepoAddCmd(out))

@ -29,6 +29,7 @@ import (
"github.com/gofrs/flock" "github.com/gofrs/flock"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"golang.org/x/crypto/ssh/terminal"
"sigs.k8s.io/yaml" "sigs.k8s.io/yaml"
"helm.sh/helm/v3/cmd/helm/require" "helm.sh/helm/v3/cmd/helm/require"
@ -41,7 +42,7 @@ type repoAddOptions struct {
url string url string
username string username string
password string password string
noUpdate bool forceUpdate bool
certFile string certFile string
keyFile string keyFile string
@ -50,6 +51,9 @@ type repoAddOptions struct {
repoFile string repoFile string
repoCache string repoCache string
// Deprecated, but cannot be removed until Helm 4
deprecatedNoUpdate bool
} }
func newRepoAddCmd(out io.Writer) *cobra.Command { func newRepoAddCmd(out io.Writer) *cobra.Command {
@ -59,6 +63,7 @@ func newRepoAddCmd(out io.Writer) *cobra.Command {
Use: "add [NAME] [URL]", Use: "add [NAME] [URL]",
Short: "add a chart repository", Short: "add a chart repository",
Args: require.ExactArgs(2), Args: require.ExactArgs(2),
ValidArgsFunction: noCompletions,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
o.name = args[0] o.name = args[0]
o.url = args[1] o.url = args[1]
@ -72,7 +77,8 @@ func newRepoAddCmd(out io.Writer) *cobra.Command {
f := cmd.Flags() f := cmd.Flags()
f.StringVar(&o.username, "username", "", "chart repository username") f.StringVar(&o.username, "username", "", "chart repository username")
f.StringVar(&o.password, "password", "", "chart repository password") f.StringVar(&o.password, "password", "", "chart repository password")
f.BoolVar(&o.noUpdate, "no-update", false, "raise error if repo is already registered") f.BoolVar(&o.forceUpdate, "force-update", false, "replace (overwrite) the repo if it already exists")
f.BoolVar(&o.deprecatedNoUpdate, "no-update", false, "Ignored. Formerly, it would disabled forced updates. It is deprecated by force-update.")
f.StringVar(&o.certFile, "cert-file", "", "identify HTTPS client using this SSL certificate file") f.StringVar(&o.certFile, "cert-file", "", "identify HTTPS client using this SSL certificate file")
f.StringVar(&o.keyFile, "key-file", "", "identify HTTPS client using this SSL key file") f.StringVar(&o.keyFile, "key-file", "", "identify HTTPS client using this SSL key file")
f.StringVar(&o.caFile, "ca-file", "", "verify certificates of HTTPS-enabled servers using this CA bundle") f.StringVar(&o.caFile, "ca-file", "", "verify certificates of HTTPS-enabled servers using this CA bundle")
@ -110,8 +116,15 @@ func (o *repoAddOptions) run(out io.Writer) error {
return err return err
} }
if o.noUpdate && f.Has(o.name) { if o.username != "" && o.password == "" {
return errors.Errorf("repository name (%s) already exists, please specify a different name", o.name) fd := int(os.Stdin.Fd())
fmt.Fprint(out, "Password: ")
password, err := terminal.ReadPassword(fd)
fmt.Fprintln(out)
if err != nil {
return err
}
o.password = string(password)
} }
c := repo.Entry{ c := repo.Entry{
@ -125,11 +138,31 @@ func (o *repoAddOptions) run(out io.Writer) error {
InsecureSkipTLSverify: o.insecureSkipTLSverify, InsecureSkipTLSverify: o.insecureSkipTLSverify,
} }
// If the repo exists do one of two things:
// 1. If the configuration for the name is the same continue without error
// 2. When the config is different require --force-update
if !o.forceUpdate && f.Has(o.name) {
existing := f.Get(o.name)
if c != *existing {
// The input coming in for the name is different from what is already
// configured. Return an error.
return errors.Errorf("repository name (%s) already exists, please specify a different name", o.name)
}
// The add is idempotent so do nothing
fmt.Fprintf(out, "%q already exists with the same configuration, skipping\n", o.name)
return nil
}
r, err := repo.NewChartRepository(&c, getter.All(settings)) r, err := repo.NewChartRepository(&c, getter.All(settings))
if err != nil { if err != nil {
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)
} }

@ -34,25 +34,50 @@ import (
) )
func TestRepoAddCmd(t *testing.T) { func TestRepoAddCmd(t *testing.T) {
srv, err := repotest.NewTempServer("testdata/testserver/*.*") srv, err := repotest.NewTempServerWithCleanup(t, "testdata/testserver/*.*")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer srv.Stop() defer srv.Stop()
repoFile := filepath.Join(ensure.TempDir(t), "repositories.yaml") // A second test server is setup to verify URL changing
srv2, err := repotest.NewTempServerWithCleanup(t, "testdata/testserver/*.*")
if err != nil {
t.Fatal(err)
}
defer srv2.Stop()
tmpdir := ensure.TempDir(t)
repoFile := filepath.Join(tmpdir, "repositories.yaml")
tests := []cmdTestCase{{ tests := []cmdTestCase{
{
name: "add a repository", name: "add a repository",
cmd: fmt.Sprintf("repo add test-name %s --repository-config %s", srv.URL(), repoFile), cmd: fmt.Sprintf("repo add test-name %s --repository-config %s --repository-cache %s", srv.URL(), repoFile, tmpdir),
golden: "output/repo-add.txt", golden: "output/repo-add.txt",
}} },
{
name: "add repository second time",
cmd: fmt.Sprintf("repo add test-name %s --repository-config %s --repository-cache %s", srv.URL(), repoFile, tmpdir),
golden: "output/repo-add2.txt",
},
{
name: "add repository different url",
cmd: fmt.Sprintf("repo add test-name %s --repository-config %s --repository-cache %s", srv2.URL(), repoFile, tmpdir),
wantError: true,
},
{
name: "add repository second time",
cmd: fmt.Sprintf("repo add test-name %s --repository-config %s --repository-cache %s --force-update", srv2.URL(), repoFile, tmpdir),
golden: "output/repo-add.txt",
},
}
runTestCmd(t, tests) runTestCmd(t, tests)
} }
func TestRepoAdd(t *testing.T) { func TestRepoAdd(t *testing.T) {
ts, err := repotest.NewTempServer("testdata/testserver/*.*") ts, err := repotest.NewTempServerWithCleanup(t, "testdata/testserver/*.*")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -66,7 +91,8 @@ func TestRepoAdd(t *testing.T) {
o := &repoAddOptions{ o := &repoAddOptions{
name: testRepoName, name: testRepoName,
url: ts.URL(), url: ts.URL(),
noUpdate: true, forceUpdate: false,
deprecatedNoUpdate: true,
repoFile: repoFile, repoFile: repoFile,
} }
os.Setenv(xdg.CacheHomeEnvVar, rootDir) os.Setenv(xdg.CacheHomeEnvVar, rootDir)
@ -93,7 +119,7 @@ func TestRepoAdd(t *testing.T) {
t.Errorf("Error cache charts file was not created for repository %s", testRepoName) t.Errorf("Error cache charts file was not created for repository %s", testRepoName)
} }
o.noUpdate = false o.forceUpdate = true
if err := o.run(ioutil.Discard); err != nil { if err := o.run(ioutil.Discard); err != nil {
t.Errorf("Repository was not updated: %s", err) t.Errorf("Repository was not updated: %s", err)
@ -117,7 +143,7 @@ func TestRepoAddConcurrentDirNotExist(t *testing.T) {
} }
func repoAddConcurrent(t *testing.T, testName, repoFile string) { func repoAddConcurrent(t *testing.T, testName, repoFile string) {
ts, err := repotest.NewTempServer("testdata/testserver/*.*") ts, err := repotest.NewTempServerWithCleanup(t, "testdata/testserver/*.*")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -131,7 +157,8 @@ func repoAddConcurrent(t *testing.T, testName, repoFile string) {
o := &repoAddOptions{ o := &repoAddOptions{
name: name, name: name,
url: ts.URL(), url: ts.URL(),
noUpdate: true, deprecatedNoUpdate: true,
forceUpdate: false,
repoFile: repoFile, repoFile: repoFile,
} }
if err := o.run(ioutil.Discard); err != nil { if err := o.run(ioutil.Discard); err != nil {
@ -159,3 +186,9 @@ func repoAddConcurrent(t *testing.T, testName, repoFile string) {
} }
} }
} }
func TestRepoAddFileCompletion(t *testing.T) {
checkFileCompletion(t, "repo add", false)
checkFileCompletion(t, "repo add reponame", false)
checkFileCompletion(t, "repo add reponame https://example.com", false)
}

@ -53,6 +53,14 @@ func newRepoIndexCmd(out io.Writer) *cobra.Command {
Short: "generate an index file given a directory containing packaged charts", Short: "generate an index file given a directory containing packaged charts",
Long: repoIndexDesc, Long: repoIndexDesc,
Args: require.ExactArgs(1), Args: require.ExactArgs(1),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 {
// Allow file completion when completing the argument for the directory
return nil, cobra.ShellCompDirectiveDefault
}
// No more completions, so disable file completion
return nil, cobra.ShellCompDirectiveNoFileComp
},
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
o.dir = args[0] o.dir = args[0]
return o.run(out) return o.run(out)

@ -165,3 +165,8 @@ func copyFile(dst, src string) error {
return err return err
} }
func TestRepoIndexFileCompletion(t *testing.T) {
checkFileCompletion(t, "repo index", true)
checkFileCompletion(t, "repo index mydir", false)
}

@ -36,9 +36,10 @@ func newRepoListCmd(out io.Writer) *cobra.Command {
Aliases: []string{"ls"}, Aliases: []string{"ls"},
Short: "list chart repositories", Short: "list chart repositories",
Args: require.NoArgs, Args: require.NoArgs,
ValidArgsFunction: noCompletions,
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")
} }
@ -97,13 +98,38 @@ func (r *repoListWriter) encodeByFormat(out io.Writer, format output.Format) err
return nil return nil
} }
// Returns all repos from repos, except those with names matching ignoredRepoNames
// Inspired by https://stackoverflow.com/a/28701031/893211
func filterRepos(repos []*repo.Entry, ignoredRepoNames []string) []*repo.Entry {
// if ignoredRepoNames is nil, just return repo
if ignoredRepoNames == nil {
return repos
}
filteredRepos := make([]*repo.Entry, 0)
ignored := make(map[string]bool, len(ignoredRepoNames))
for _, repoName := range ignoredRepoNames {
ignored[repoName] = true
}
for _, repo := range repos {
if _, removed := ignored[repo.Name]; !removed {
filteredRepos = append(filteredRepos, repo)
}
}
return filteredRepos
}
// Provide dynamic auto-completion for repo names // Provide dynamic auto-completion for repo names
func compListRepos(prefix string) []string { func compListRepos(prefix string, ignoredRepoNames []string) []string {
var rNames []string var rNames []string
f, err := repo.LoadFile(settings.RepositoryConfig) f, err := repo.LoadFile(settings.RepositoryConfig)
if err == nil && len(f.Repositories) > 0 { if err == nil && len(f.Repositories) > 0 {
for _, repo := range f.Repositories { filteredRepos := filterRepos(f.Repositories, ignoredRepoNames)
for _, repo := range filteredRepos {
if strings.HasPrefix(repo.Name, prefix) { if strings.HasPrefix(repo.Name, prefix) {
rNames = append(rNames, repo.Name) rNames = append(rNames, repo.Name)
} }

@ -23,3 +23,7 @@ import (
func TestRepoListOutputCompletion(t *testing.T) { func TestRepoListOutputCompletion(t *testing.T) {
outputFlagCompletionTest(t, "repo list") outputFlagCompletionTest(t, "repo list")
} }
func TestRepoListFileCompletion(t *testing.T) {
checkFileCompletion(t, "repo list", false)
}

@ -26,13 +26,12 @@ 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"
) )
type repoRemoveOptions struct { type repoRemoveOptions struct {
name string names []string
repoFile string repoFile string
repoCache string repoCache string
} }
@ -41,26 +40,20 @@ func newRepoRemoveCmd(out io.Writer) *cobra.Command {
o := &repoRemoveOptions{} o := &repoRemoveOptions{}
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "remove [NAME]", Use: "remove [REPO1 [REPO2 ...]]",
Aliases: []string{"rm"}, Aliases: []string{"rm"},
Short: "remove a chart repository", Short: "remove one or more chart repositories",
Args: require.ExactArgs(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
o.name = args[0] o.names = args
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 compListRepos(toComplete), completion.BashCompDirectiveNoFileComp
})
return cmd return cmd
} }
@ -70,18 +63,20 @@ func (o *repoRemoveOptions) run(out io.Writer) error {
return errors.New("no repositories configured") return errors.New("no repositories configured")
} }
if !r.Remove(o.name) { for _, name := range o.names {
return errors.Errorf("no repo named %q found", o.name) if !r.Remove(name) {
return errors.Errorf("no repo named %q found", name)
} }
if err := r.WriteFile(o.repoFile, 0644); err != nil { if err := r.WriteFile(o.repoFile, 0644); err != nil {
return err return err
} }
if err := removeRepoCache(o.repoCache, o.name); err != nil { if err := removeRepoCache(o.repoCache, name); err != nil {
return err return err
} }
fmt.Fprintf(out, "%q has been removed from your repositories\n", name)
}
fmt.Fprintf(out, "%q has been removed from your repositories\n", o.name)
return nil return nil
} }

@ -30,7 +30,7 @@ import (
) )
func TestRepoRemove(t *testing.T) { func TestRepoRemove(t *testing.T) {
ts, err := repotest.NewTempServer("testdata/testserver/*.*") ts, err := repotest.NewTempServerWithCleanup(t, "testdata/testserver/*.*")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -44,7 +44,7 @@ func TestRepoRemove(t *testing.T) {
b := bytes.NewBuffer(nil) b := bytes.NewBuffer(nil)
rmOpts := repoRemoveOptions{ rmOpts := repoRemoveOptions{
name: testRepoName, names: []string{testRepoName},
repoFile: repoFile, repoFile: repoFile,
repoCache: rootDir, repoCache: rootDir,
} }
@ -62,14 +62,9 @@ func TestRepoRemove(t *testing.T) {
t.Error(err) t.Error(err)
} }
idx := filepath.Join(rootDir, helmpath.CacheIndexFile(testRepoName)) cacheIndexFile, cacheChartsFile := createCacheFiles(rootDir, testRepoName)
mf, _ := os.Create(idx)
mf.Close()
idx2 := filepath.Join(rootDir, helmpath.CacheChartsFile(testRepoName))
mf, _ = os.Create(idx2)
mf.Close()
// Reset the buffer before running repo remove
b.Reset() b.Reset()
if err := rmOpts.run(b); err != nil { if err := rmOpts.run(b); err != nil {
@ -79,20 +74,94 @@ func TestRepoRemove(t *testing.T) {
t.Errorf("Unexpected output: %s", b.String()) t.Errorf("Unexpected output: %s", b.String())
} }
if _, err := os.Stat(idx); err == nil { testCacheFiles(t, cacheIndexFile, cacheChartsFile, testRepoName)
t.Errorf("Error cache index file was not removed for repository %s", testRepoName)
f, err := repo.LoadFile(repoFile)
if err != nil {
t.Error(err)
} }
if _, err := os.Stat(idx2); err == nil { if f.Has(testRepoName) {
t.Errorf("Error cache chart file was not removed for repository %s", testRepoName) t.Errorf("%s was not successfully removed from repositories list", testRepoName)
} }
// Test removal of multiple repos in one go
var testRepoNames = []string{"foo", "bar", "baz"}
cacheFiles := make(map[string][]string, len(testRepoNames))
// Add test repos
for _, repoName := range testRepoNames {
o := &repoAddOptions{
name: repoName,
url: ts.URL(),
repoFile: repoFile,
}
if err := o.run(os.Stderr); err != nil {
t.Error(err)
}
cacheIndex, cacheChart := createCacheFiles(rootDir, repoName)
cacheFiles[repoName] = []string{cacheIndex, cacheChart}
}
// Create repo remove command
multiRmOpts := repoRemoveOptions{
names: testRepoNames,
repoFile: repoFile,
repoCache: rootDir,
}
// Reset the buffer before running repo remove
b.Reset()
// Run repo remove command
if err := multiRmOpts.run(b); err != nil {
t.Errorf("Error removing list of repos from repositories: %q", testRepoNames)
}
// Check that stuff were removed
if !strings.Contains(b.String(), "has been removed") {
t.Errorf("Unexpected output: %s", b.String())
}
for _, repoName := range testRepoNames {
f, err := repo.LoadFile(repoFile) f, err := repo.LoadFile(repoFile)
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
if f.Has(repoName) {
t.Errorf("%s was not successfully removed from repositories list", repoName)
}
cacheIndex := cacheFiles[repoName][0]
cacheChart := cacheFiles[repoName][1]
testCacheFiles(t, cacheIndex, cacheChart, repoName)
}
}
if f.Has(testRepoName) { func createCacheFiles(rootDir string, repoName string) (cacheIndexFile string, cacheChartsFile string) {
t.Errorf("%s was not successfully removed from repositories list", testRepoName) cacheIndexFile = filepath.Join(rootDir, helmpath.CacheIndexFile(repoName))
mf, _ := os.Create(cacheIndexFile)
mf.Close()
cacheChartsFile = filepath.Join(rootDir, helmpath.CacheChartsFile(repoName))
mf, _ = os.Create(cacheChartsFile)
mf.Close()
return cacheIndexFile, cacheChartsFile
}
func testCacheFiles(t *testing.T, cacheIndexFile string, cacheChartsFile string, repoName string) {
if _, err := os.Stat(cacheIndexFile); err == nil {
t.Errorf("Error cache index file was not removed for repository %s", repoName)
} }
if _, err := os.Stat(cacheChartsFile); err == nil {
t.Errorf("Error cache chart file was not removed for repository %s", repoName)
}
}
func TestRepoRemoveFileCompletion(t *testing.T) {
checkFileCompletion(t, "repo remove", false)
checkFileCompletion(t, "repo remove repo1", false)
} }

@ -0,0 +1,25 @@
/*
Copyright The Helm Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"testing"
)
func TestRepoFileCompletion(t *testing.T) {
checkFileCompletion(t, "repo", false)
}

@ -39,6 +39,7 @@ var errNoRepositories = errors.New("no repositories found. You must add one befo
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 {
@ -50,8 +51,10 @@ func newRepoUpdateCmd(out io.Writer) *cobra.Command {
Short: "update information of available charts locally from chart repositories", Short: "update information of available charts locally from chart repositories",
Long: updateDesc, Long: updateDesc,
Args: require.NoArgs, Args: require.NoArgs,
ValidArgsFunction: noCompletions,
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 +72,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,11 +52,30 @@ 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)()
ts, err := repotest.NewTempServer("testdata/testserver/*.*") ts, err := repotest.NewTempServerWithCleanup(t, "testdata/testserver/*.*")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -79,3 +100,7 @@ func TestUpdateCharts(t *testing.T) {
t.Error("Update was not successful") t.Error("Update was not successful")
} }
} }
func TestRepoUpdateFileCompletion(t *testing.T) {
checkFileCompletion(t, "repo update", false)
}

@ -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")
@ -82,6 +84,7 @@ func newRollbackCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
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(&client.Wait, "wait", false, "if set, will wait until all Pods, PVCs, Services, and minimum number of Pods of a Deployment, StatefulSet, or ReplicaSet are in a ready state before marking the release as successful. It will wait for as long as --timeout") f.BoolVar(&client.Wait, "wait", false, "if set, will wait until all Pods, PVCs, Services, and minimum number of Pods of a Deployment, StatefulSet, or ReplicaSet are in a ready state before marking the release as successful. It will wait for as long as --timeout")
f.BoolVar(&client.CleanupOnFail, "cleanup-on-fail", false, "allow deletion of new resources created in this rollback when rollback fails") f.BoolVar(&client.CleanupOnFail, "cleanup-on-fail", false, "allow deletion of new resources created in this rollback when rollback fails")
f.IntVar(&client.MaxHistory, "history-max", settings.MaxHistory, "limit the maximum number of revisions saved per release. Use 0 for no limit")
return cmd return cmd
} }

@ -68,3 +68,45 @@ 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)
}
func TestRollbackFileCompletion(t *testing.T) {
checkFileCompletion(t, "rollback", false)
checkFileCompletion(t, "rollback myrelease", false)
checkFileCompletion(t, "rollback myrelease 1", false)
}

@ -17,8 +17,10 @@ limitations under the License.
package main // import "helm.sh/helm/v3/cmd/helm" package main // import "helm.sh/helm/v3/cmd/helm"
import ( import (
"context"
"fmt" "fmt"
"io" "io"
"log"
"strings" "strings"
"github.com/spf13/cobra" "github.com/spf13/cobra"
@ -26,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"
) )
@ -42,72 +43,86 @@ Common actions for Helm:
Environment variables: Environment variables:
+------------------+-----------------------------------------------------------------------------+
| Name | Description | | Name | Description |
+------------------+-----------------------------------------------------------------------------+ |------------------------------------|-----------------------------------------------------------------------------------|
| $XDG_CACHE_HOME | set an alternative location for storing cached files. | | $HELM_CACHE_HOME | set an alternative location for storing cached files. |
| $XDG_CONFIG_HOME | set an alternative location for storing Helm configuration. | | $HELM_CONFIG_HOME | set an alternative location for storing Helm configuration. |
| $XDG_DATA_HOME | set an alternative location for storing Helm data. | | $HELM_DATA_HOME | set an alternative location for storing Helm data. |
| $HELM_DRIVER | set the backend storage driver. Values are: configmap, secret, memory | | $HELM_DEBUG | indicate whether or not Helm is running in Debug mode |
| $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_MAX_HISTORY | set the maximum number of helm release history. |
| $HELM_NAMESPACE | set the namespace used for the helm operations. |
| $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. |
| $HELM_PLUGINS | set the path to the plugins directory |
| $HELM_REGISTRY_CONFIG | set the path to the registry config file. |
| $HELM_REPOSITORY_CACHE | set the path to the repository cache directory |
| $HELM_REPOSITORY_CONFIG | set the path to the repositories file. |
| $KUBECONFIG | set an alternative Kubernetes configuration file (default "~/.kube/config") | | $KUBECONFIG | set an alternative Kubernetes configuration file (default "~/.kube/config") |
+------------------+-----------------------------------------------------------------------------+ | $HELM_KUBEAPISERVER | set the Kubernetes API Server Endpoint for authentication |
| $HELM_KUBEASGROUPS | set the Username to impersonate for the operation. |
| $HELM_KUBEASUSER | set the Groups to use for impoersonation using a comma-separated list. |
| $HELM_KUBECONTEXT | set the name of the kubeconfig context. |
| $HELM_KUBETOKEN | set the Bearer KubeToken used for authentication. |
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(), // This breaks completion for 'helm help <TAB>'
// The Cobra release following 1.0 will fix this
//ValidArgsFunction: noCompletions, // Disable file completion
} }
flags := cmd.PersistentFlags() flags := cmd.PersistentFlags()
settings.AddFlags(flags) settings.AddFlags(flags)
addKlogFlags(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(metav1.ListOptions{TimeoutSeconds: &to}); err == nil { if namespaces, err := client.CoreV1().Namespaces().List(context.Background(), metav1.ListOptions{TimeoutSeconds: &to}); err == nil {
for _, ns := range namespaces.Items { for _, ns := range namespaces.Items {
if strings.HasPrefix(ns.Name, toComplete) { if strings.HasPrefix(ns.Name, toComplete) {
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 {
@ -122,11 +137,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
@ -166,19 +185,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(
@ -189,5 +205,8 @@ 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 // Check permissions on critical files
checkPerms()
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 {
@ -103,3 +121,11 @@ func TestUnknownSubCmd(t *testing.T) {
t.Errorf("Expect unknown command error, got %q", err) t.Errorf("Expect unknown command error, got %q", err)
} }
} }
// Need the release of Cobra following 1.0 to be able to disable
// file completion on the root command. Until then, we cannot
// because it would break 'helm help <TAB>'
//
// func TestRootFileCompletion(t *testing.T) {
// checkFileCompletion(t, "", false)
// }

@ -0,0 +1,58 @@
// +build !windows
/*
Copyright The Helm Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"os"
"os/user"
"path/filepath"
)
func checkPerms() {
// This function MUST NOT FAIL, as it is just a check for a common permissions problem.
// If for some reason the function hits a stopping condition, it may panic. But only if
// we can be sure that it is panicing because Helm cannot proceed.
kc := settings.KubeConfig
if kc == "" {
kc = os.Getenv("KUBECONFIG")
}
if kc == "" {
u, err := user.Current()
if err != nil {
// No idea where to find KubeConfig, so return silently. Many helm commands
// can proceed happily without a KUBECONFIG, so this is not a fatal error.
return
}
kc = filepath.Join(u.HomeDir, ".kube", "config")
}
fi, err := os.Stat(kc)
if err != nil {
// DO NOT error if no KubeConfig is found. Not all commands require one.
return
}
perm := fi.Mode().Perm()
if perm&0040 > 0 {
warning("Kubernetes configuration file is group-readable. This is insecure. Location: %s", kc)
}
if perm&0004 > 0 {
warning("Kubernetes configuration file is world-readable. This is insecure. Location: %s", kc)
}
}

@ -0,0 +1,87 @@
// +build !windows
/*
Copyright The Helm Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"bytes"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"
)
func checkPermsStderr() (string, error) {
r, w, err := os.Pipe()
if err != nil {
return "", err
}
stderr := os.Stderr
os.Stderr = w
defer func() {
os.Stderr = stderr
}()
checkPerms()
w.Close()
var text bytes.Buffer
io.Copy(&text, r)
return text.String(), nil
}
func TestCheckPerms(t *testing.T) {
tdir, err := ioutil.TempDir("", "helmtest")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tdir)
tfile := filepath.Join(tdir, "testconfig")
fh, err := os.OpenFile(tfile, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0440)
if err != nil {
t.Errorf("Failed to create temp file: %s", err)
}
tconfig := settings.KubeConfig
settings.KubeConfig = tfile
defer func() { settings.KubeConfig = tconfig }()
text, err := checkPermsStderr()
if err != nil {
t.Fatalf("could not read from stderr: %s", err)
}
expectPrefix := "WARNING: Kubernetes configuration file is group-readable. This is insecure. Location:"
if !strings.HasPrefix(text, expectPrefix) {
t.Errorf("Expected to get a warning for group perms. Got %q", text)
}
if err := fh.Chmod(0404); err != nil {
t.Errorf("Could not change mode on file: %s", err)
}
text, err = checkPermsStderr()
if err != nil {
t.Fatalf("could not read from stderr: %s", err)
}
expectPrefix = "WARNING: Kubernetes configuration file is world-readable. This is insecure. Location:"
if !strings.HasPrefix(text, expectPrefix) {
t.Errorf("Expected to get a warning for world perms. Got %q", text)
}
}

@ -0,0 +1,22 @@
/*
Copyright The Helm Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
func checkPerms() {
// Not yet implemented on Windows. If you know how to do a comprehensive perms
// check on Windows, contributions welcomed!
}

@ -34,6 +34,7 @@ func newSearchCmd(out io.Writer) *cobra.Command {
Use: "search [keyword]", Use: "search [keyword]",
Short: "search for a keyword in charts", Short: "search for a keyword in charts",
Long: searchDesc, Long: searchDesc,
ValidArgsFunction: noCompletions, // Disable file completion
} }
cmd.AddCommand(newSearchHubCmd(out)) cmd.AddCommand(newSearchHubCmd(out))

@ -54,3 +54,7 @@ func TestSearchHubCmd(t *testing.T) {
func TestSearchHubOutputCompletion(t *testing.T) { func TestSearchHubOutputCompletion(t *testing.T) {
outputFlagCompletionTest(t, "search hub") outputFlagCompletionTest(t, "search hub")
} }
func TestSearchHubFileCompletion(t *testing.T) {
checkFileCompletion(t, "search hub", true) // File completion may be useful when inputing a keyword
}

@ -22,7 +22,6 @@ import (
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
"os"
"path/filepath" "path/filepath"
"strings" "strings"
@ -32,7 +31,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"
@ -185,7 +183,7 @@ func (o *searchRepoOptions) buildIndex() (*search.Index, error) {
f := filepath.Join(o.repoCacheDir, helmpath.CacheIndexFile(n)) f := filepath.Join(o.repoCacheDir, helmpath.CacheIndexFile(n))
ind, err := repo.LoadIndexFile(f) ind, err := repo.LoadIndexFile(f)
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "WARNING: Repo %q is corrupt or missing. Try 'helm repo update'.", n) warning("Repo %q is corrupt or missing. Try 'helm repo update'.", n)
continue continue
} }
@ -290,15 +288,15 @@ 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
var completions []string var completions []string
// First check completions for repos // First check completions for repos
repos := compListRepos("") repos := compListRepos("", nil)
for _, repo := range repos { for _, repo := range repos {
repoWithSlash := fmt.Sprintf("%s/", repo) repoWithSlash := fmt.Sprintf("%s/", repo)
if strings.HasPrefix(toComplete, repoWithSlash) { if strings.HasPrefix(toComplete, repoWithSlash) {
@ -312,7 +310,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 +326,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,25 +345,30 @@ 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)
} }
if !includeFiles {
// If we should not include files in the completions,
// we should disable file completion
directive = directive | cobra.ShellCompDirectiveNoFileComp
}
return completions, directive return completions, directive
} }
@ -380,7 +383,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
} }

@ -87,3 +87,7 @@ func TestSearchRepositoriesCmd(t *testing.T) {
func TestSearchRepoOutputCompletion(t *testing.T) { func TestSearchRepoOutputCompletion(t *testing.T) {
outputFlagCompletionTest(t, "search repo") outputFlagCompletionTest(t, "search repo")
} }
func TestSearchRepoFileCompletion(t *testing.T) {
checkFileCompletion(t, "search repo", true) // File completion may be useful when inputing a keyword
}

@ -0,0 +1,23 @@
/*
Copyright The Helm Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import "testing"
func TestSearchFileCompletion(t *testing.T) {
checkFileCompletion(t, "search", false)
}

@ -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"
) )
@ -60,21 +60,23 @@ func newShowCmd(out io.Writer) *cobra.Command {
Aliases: []string{"inspect"}, Aliases: []string{"inspect"},
Long: showDesc, Long: showDesc,
Args: require.NoArgs, Args: require.NoArgs,
ValidArgsFunction: noCompletions, // Disable file completion
} }
// 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)
@ -88,9 +90,10 @@ 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)
@ -104,9 +107,10 @@ 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)
@ -120,9 +124,10 @@ 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 +141,32 @@ 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")
if subCmd.Name() == "values" {
f.StringVar(&client.JSONPathTemplate, "jsonpath", "", "supply a JSONPath expression to filter the output")
}
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) {

@ -26,7 +26,7 @@ import (
) )
func TestShowPreReleaseChart(t *testing.T) { func TestShowPreReleaseChart(t *testing.T) {
srv, err := repotest.NewTempServer("testdata/testcharts/*.tgz*") srv, err := repotest.NewTempServerWithCleanup(t, "testdata/testcharts/*.tgz*")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -49,6 +49,13 @@ func TestShowPreReleaseChart(t *testing.T) {
fail: true, fail: true,
expectedErr: "failed to download \"test/pre-release-chart\"", expectedErr: "failed to download \"test/pre-release-chart\"",
}, },
{
name: "show pre-release chart",
args: "test/pre-release-chart",
fail: true,
flags: "--version 1.0.0",
expectedErr: "failed to download \"test/pre-release-chart\" at version \"1.0.0\"",
},
{ {
name: "show pre-release chart with 'devel' flag", name: "show pre-release chart with 'devel' flag",
args: "test/pre-release-chart", args: "test/pre-release-chart",
@ -80,3 +87,61 @@ 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)
}
func TestShowFileCompletion(t *testing.T) {
checkFileCompletion(t, "show", false)
}
func TestShowAllFileCompletion(t *testing.T) {
checkFileCompletion(t, "show all", true)
}
func TestShowChartFileCompletion(t *testing.T) {
checkFileCompletion(t, "show chart", true)
}
func TestShowReadmeFileCompletion(t *testing.T) {
checkFileCompletion(t, "show readme", true)
}
func TestShowValuesFileCompletion(t *testing.T) {
checkFileCompletion(t, "show values", true)
}

@ -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"
@ -39,6 +39,8 @@ The status consists of:
- last deployment time - last deployment time
- k8s namespace in which the release lives - k8s namespace in which the release lives
- state of the release (can be: unknown, deployed, uninstalled, superseded, failed, uninstalling, pending-install, pending-upgrade or pending-rollback) - state of the release (can be: unknown, deployed, uninstalled, superseded, failed, uninstalling, pending-install, pending-upgrade or pending-rollback)
- revision of the release
- description of the release (can be completion message or error message, need to enable --show-desc)
- list of resources that this release consists of, sorted by kind - list of resources that this release consists of, sorted by kind
- details on last test suite run, if applicable - details on last test suite run, if applicable
- additional notes provided by the chart - additional notes provided by the chart
@ -50,9 +52,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 {
@ -62,30 +70,27 @@ func newStatusCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
// strip chart metadata from the output // strip chart metadata from the output
rel.Chart = nil rel.Chart = nil
return outfmt.Write(out, &statusPrinter{rel, false}) return outfmt.Write(out, &statusPrinter{rel, false, client.ShowDescription})
}, },
} }
// 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)
f.BoolVar(&client.ShowDescription, "show-desc", false, "if set, display the description message of the named release")
return cmd return cmd
} }
@ -93,6 +98,7 @@ func newStatusCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
type statusPrinter struct { type statusPrinter struct {
release *release.Release release *release.Release
debug bool debug bool
showDescription bool
} }
func (s statusPrinter) WriteJSON(out io.Writer) error { func (s statusPrinter) WriteJSON(out io.Writer) error {
@ -114,6 +120,9 @@ func (s statusPrinter) WriteTable(out io.Writer) error {
fmt.Fprintf(out, "NAMESPACE: %s\n", s.release.Namespace) fmt.Fprintf(out, "NAMESPACE: %s\n", s.release.Namespace)
fmt.Fprintf(out, "STATUS: %s\n", s.release.Info.Status.String()) fmt.Fprintf(out, "STATUS: %s\n", s.release.Info.Status.String())
fmt.Fprintf(out, "REVISION: %d\n", s.release.Version) fmt.Fprintf(out, "REVISION: %d\n", s.release.Version)
if s.showDescription {
fmt.Fprintf(out, "DESCRIPTION: %s\n", s.release.Info.Description)
}
executions := executionsByHookEvent(s.release) executions := executionsByHookEvent(s.release)
if tests, ok := executions[release.HookTest]; !ok || len(tests) == 0 { if tests, ok := executions[release.HookTest]; !ok || len(tests) == 0 {

@ -44,6 +44,14 @@ func TestStatusCmd(t *testing.T) {
rels: releasesMockWithStatus(&release.Info{ rels: releasesMockWithStatus(&release.Info{
Status: release.StatusDeployed, Status: release.StatusDeployed,
}), }),
}, {
name: "get status of a deployed release, with desc",
cmd: "status --show-desc flummoxed-chickadee",
golden: "output/status-with-desc.txt",
rels: releasesMockWithStatus(&release.Info{
Status: release.StatusDeployed,
Description: "Mock description",
}),
}, { }, {
name: "get status of a deployed release with notes", name: "get status of a deployed release with notes",
cmd: "status flummoxed-chickadee", cmd: "status flummoxed-chickadee",
@ -171,3 +179,8 @@ func TestStatusRevisionCompletion(t *testing.T) {
func TestStatusOutputCompletion(t *testing.T) { func TestStatusOutputCompletion(t *testing.T) {
outputFlagCompletionTest(t, "status") outputFlagCompletionTest(t, "status")
} }
func TestStatusFileCompletion(t *testing.T) {
checkFileCompletion(t, "status", false)
checkFileCompletion(t, "status myrelease", false)
}

@ -20,14 +20,16 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"io" "io"
"os"
"path"
"path/filepath" "path/filepath"
"regexp" "regexp"
"sort"
"strings" "strings"
"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"
@ -55,6 +57,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"
@ -76,22 +81,46 @@ func newTemplateCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
if rel != nil { if rel != nil {
var manifests bytes.Buffer var manifests bytes.Buffer
fmt.Fprintln(&manifests, strings.TrimSpace(rel.Manifest)) fmt.Fprintln(&manifests, strings.TrimSpace(rel.Manifest))
if !client.DisableHooks { if !client.DisableHooks {
fileWritten := make(map[string]bool)
for _, m := range rel.Hooks { for _, m := range rel.Hooks {
if client.OutputDir == "" {
fmt.Fprintf(&manifests, "---\n# Source: %s\n%s\n", m.Path, m.Manifest) fmt.Fprintf(&manifests, "---\n# Source: %s\n%s\n", m.Path, m.Manifest)
} else {
newDir := client.OutputDir
if client.UseReleaseName {
newDir = filepath.Join(client.OutputDir, client.ReleaseName)
}
err = writeToFile(newDir, m.Path, m.Manifest, fileWritten[m.Path])
if err != nil {
return err
}
fileWritten[m.Path] = true
}
} }
} }
// 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 {
// This is necessary to ensure consistent manifest ordering when using --show-only
// with globs or directory names.
splitManifests := releaseutil.SplitManifests(manifests.String()) splitManifests := releaseutil.SplitManifests(manifests.String())
manifestsKeys := make([]string, 0, len(splitManifests))
for k := range splitManifests {
manifestsKeys = append(manifestsKeys, k)
}
sort.Sort(releaseutil.BySplitManifestsOrder(manifestsKeys))
manifestNameRegex := regexp.MustCompile("# Source: [^/]+/(.+)") manifestNameRegex := regexp.MustCompile("# Source: [^/]+/(.+)")
var manifestsToRender []string var manifestsToRender []string
for _, f := range showFiles { for _, f := range showFiles {
missing := true missing := true
for _, manifest := range splitManifests { // Use linux-style filepath separators to unify user's input path
f = filepath.ToSlash(f)
for _, manifestKey := range manifestsKeys {
manifest := splitManifests[manifestKey]
submatch := manifestNameRegex.FindStringSubmatch(manifest) submatch := manifestNameRegex.FindStringSubmatch(manifest)
if len(submatch) == 0 { if len(submatch) == 0 {
continue continue
@ -100,15 +129,18 @@ 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
if f == manifestPath { if matched, _ := filepath.Match(f, manifestPath); !matched {
continue
}
manifestsToRender = append(manifestsToRender, manifest) manifestsToRender = append(manifestsToRender, manifest)
missing = false missing = false
} }
}
if missing { if missing {
return fmt.Errorf("could not find template %s in chart", f) return fmt.Errorf("could not find template %s in chart", f)
} }
@ -125,13 +157,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")
@ -143,3 +170,50 @@ func newTemplateCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
return cmd return cmd
} }
// The following functions (writeToFile, createOrOpenFile, and ensureDirectoryForFile)
// are coppied from the actions package. This is part of a change to correct a
// bug introduced by #8156. As part of the todo to refactor renderResources
// this duplicate code should be removed. It is added here so that the API
// surface area is as minimally impacted as possible in fixing the issue.
func writeToFile(outputDir string, name string, data string, append bool) error {
outfileName := strings.Join([]string{outputDir, name}, string(filepath.Separator))
err := ensureDirectoryForFile(outfileName)
if err != nil {
return err
}
f, err := createOrOpenFile(outfileName, append)
if err != nil {
return err
}
defer f.Close()
_, err = f.WriteString(fmt.Sprintf("---\n# Source: %s\n%s\n", name, data))
if err != nil {
return err
}
fmt.Printf("wrote %s\n", outfileName)
return nil
}
func createOrOpenFile(filename string, append bool) (*os.File, error) {
if append {
return os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0600)
}
return os.Create(filename)
}
func ensureDirectoryForFile(file string) error {
baseDir := path.Dir(file)
_, err := os.Stat(baseDir)
if err != nil && !os.IsNotExist(err) {
return err
}
return os.MkdirAll(baseDir, 0755)
}

@ -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{
@ -94,6 +94,13 @@ func TestTemplateCmd(t *testing.T) {
cmd: fmt.Sprintf("template '%s' --show-only templates/service.yaml --show-only charts/subcharta/templates/service.yaml", chartPath), cmd: fmt.Sprintf("template '%s' --show-only templates/service.yaml --show-only charts/subcharta/templates/service.yaml", chartPath),
golden: "output/template-show-only-multiple.txt", golden: "output/template-show-only-multiple.txt",
}, },
{
name: "template with show-only glob",
cmd: fmt.Sprintf("template '%s' --show-only templates/subdir/role*", chartPath),
golden: "output/template-show-only-glob.txt",
// Repeat to ensure manifest ordering regressions are caught
repeat: 10,
},
{ {
name: "sorted output of manifests (order of filenames, then order of objects within each YAML file)", name: "sorted output of manifests (order of filenames, then order of objects within each YAML file)",
cmd: fmt.Sprintf("template '%s'", "testdata/testcharts/object-order"), cmd: fmt.Sprintf("template '%s'", "testdata/testcharts/object-order"),
@ -117,3 +124,40 @@ 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)
}
func TestTemplateFileCompletion(t *testing.T) {
checkFileCompletion(t, "template", false)
checkFileCompletion(t, "template --generate-name", true)
checkFileCompletion(t, "template myname", true)
checkFileCompletion(t, "template myname mychart", false)
}

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

@ -0,0 +1,8 @@
NAME: updeps
LAST DEPLOYED: Fri Sep 2 22:04:05 1977
NAMESPACE: default
STATUS: deployed
REVISION: 1
TEST SUITE: None
NOTES:
PARENT NOTES

@ -1,5 +1,5 @@
NAME VERSION REPOSITORY STATUS NAME VERSION REPOSITORY STATUS
reqsubchart 0.1.0 https://example.com/charts missing reqsubchart 0.1.0 https://example.com/charts unpacked
reqsubchart2 0.2.0 https://example.com/charts missing reqsubchart2 0.2.0 https://example.com/charts unpacked
reqsubchart3 >=0.1.0 https://example.com/charts missing reqsubchart3 >=0.1.0 https://example.com/charts unpacked

@ -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

@ -0,0 +1,18 @@
HELM_BIN
HELM_CACHE_HOME
HELM_CONFIG_HOME
HELM_DATA_HOME
HELM_DEBUG
HELM_KUBEAPISERVER
HELM_KUBEASGROUPS
HELM_KUBEASUSER
HELM_KUBECONTEXT
HELM_KUBETOKEN
HELM_MAX_HISTORY
HELM_NAMESPACE
HELM_PLUGINS
HELM_REGISTRY_CONFIG
HELM_REPOSITORY_CACHE
HELM_REPOSITORY_CONFIG
:4
Completion ended with directive: ShellCompDirectiveNoFileComp

@ -1,6 +1,8 @@
==> Linting testdata/testcharts/chart-with-bad-subcharts ==> Linting testdata/testcharts/chart-with-bad-subcharts
[INFO] Chart.yaml: icon is recommended [INFO] Chart.yaml: icon is recommended
[WARNING] templates/: directory not found [WARNING] templates/: directory not found
[ERROR] : unable to load chart
error unpacking bad-subchart in chart-with-bad-subcharts: validation: chart.metadata.name is required
==> Linting testdata/testcharts/chart-with-bad-subcharts/charts/bad-subchart ==> Linting testdata/testcharts/chart-with-bad-subcharts/charts/bad-subchart
[ERROR] Chart.yaml: name is required [ERROR] Chart.yaml: name is required
@ -8,9 +10,11 @@
[ERROR] Chart.yaml: version is required [ERROR] Chart.yaml: version is required
[INFO] Chart.yaml: icon is recommended [INFO] Chart.yaml: icon is recommended
[WARNING] templates/: directory not found [WARNING] templates/: directory not found
[ERROR] : unable to load chart
validation: chart.metadata.name is required
==> Linting testdata/testcharts/chart-with-bad-subcharts/charts/good-subchart ==> Linting testdata/testcharts/chart-with-bad-subcharts/charts/good-subchart
[INFO] Chart.yaml: icon is recommended [INFO] Chart.yaml: icon is recommended
[WARNING] templates/: directory not found [WARNING] templates/: directory not found
Error: 3 chart(s) linted, 1 chart(s) failed Error: 3 chart(s) linted, 2 chart(s) failed

@ -1,5 +1,7 @@
==> Linting testdata/testcharts/chart-with-bad-subcharts ==> Linting testdata/testcharts/chart-with-bad-subcharts
[INFO] Chart.yaml: icon is recommended [INFO] Chart.yaml: icon is recommended
[WARNING] templates/: directory not found [WARNING] templates/: directory not found
[ERROR] : unable to load chart
error unpacking bad-subchart in chart-with-bad-subcharts: validation: chart.metadata.name is required
1 chart(s) linted, 0 chart(s) failed Error: 1 chart(s) linted, 1 chart(s) failed

@ -0,0 +1 @@
["hummingbird","iguana","rocket","starlord"]

@ -0,0 +1,4 @@
- hummingbird
- iguana
- rocket
- starlord

@ -1,4 +1,5 @@
table table
json json
yaml yaml
:0 :4
Completion ended with directive: ShellCompDirectiveNoFileComp

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

Loading…
Cancel
Save