summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.github/workflows/check_cirrus_cron.yml2
-rw-r--r--.golangci.yml29
-rw-r--r--Makefile2
-rw-r--r--README.md2
-rw-r--r--RELEASE_NOTES.md27
-rw-r--r--cmd/podman/containers/ps.go12
-rw-r--r--cmd/podman/secrets/create.go2
-rw-r--r--contrib/cirrus/cron-fail_addrs.csv2
-rw-r--r--contrib/spec/podman.spec.in23
-rw-r--r--dependencies/dependencies.go2
-rw-r--r--go.mod2
-rw-r--r--go.sum4
-rwxr-xr-xhack/golangci-lint.sh2
-rw-r--r--libpod/container_inspect.go4
-rw-r--r--libpod/container_internal.go75
-rw-r--r--libpod/container_internal_linux.go17
-rw-r--r--libpod/define/container_inspect.go4
-rw-r--r--libpod/volume.go11
-rw-r--r--pkg/api/handlers/compat/images_push.go41
-rw-r--r--pkg/api/handlers/compat/networks.go5
-rw-r--r--pkg/domain/infra/abi/manifest.go2
-rw-r--r--test/apiv2/12-imagesMore.at18
-rw-r--r--test/apiv2/rest_api/test_rest_v2_0_0.py8
-rw-r--r--test/e2e/inspect_test.go24
-rw-r--r--test/e2e/ps_test.go17
-rw-r--r--test/e2e/run_volume_test.go18
-rw-r--r--test/system/600-completion.bats22
-rw-r--r--vendor/github.com/spf13/cobra/.golangci.yml48
-rw-r--r--vendor/github.com/spf13/cobra/.travis.yml15
-rw-r--r--vendor/github.com/spf13/cobra/CHANGELOG.md31
-rw-r--r--vendor/github.com/spf13/cobra/CONDUCT.md37
-rw-r--r--vendor/github.com/spf13/cobra/Makefile18
-rw-r--r--vendor/github.com/spf13/cobra/README.md32
-rw-r--r--vendor/github.com/spf13/cobra/bash_completions.go133
-rw-r--r--vendor/github.com/spf13/cobra/bash_completions.md2
-rw-r--r--vendor/github.com/spf13/cobra/cobra.go15
-rw-r--r--vendor/github.com/spf13/cobra/command.go116
-rw-r--r--vendor/github.com/spf13/cobra/custom_completions.go4
-rw-r--r--vendor/github.com/spf13/cobra/fish_completions.go6
-rw-r--r--vendor/github.com/spf13/cobra/go.mod4
-rw-r--r--vendor/github.com/spf13/cobra/go.sum4
-rw-r--r--vendor/github.com/spf13/cobra/powershell_completions.go323
-rw-r--r--vendor/github.com/spf13/cobra/powershell_completions.md15
-rw-r--r--vendor/github.com/spf13/cobra/projects_using_cobra.md3
-rw-r--r--vendor/github.com/spf13/cobra/shell_completions.md119
-rw-r--r--vendor/github.com/spf13/cobra/zsh_completions.go4
-rw-r--r--vendor/gopkg.in/yaml.v2/.travis.yml1
-rw-r--r--vendor/gopkg.in/yaml.v2/apic.go6
-rw-r--r--vendor/gopkg.in/yaml.v2/go.mod8
-rw-r--r--vendor/gopkg.in/yaml.v2/yaml.go14
-rw-r--r--vendor/modules.txt4
-rw-r--r--version/version.go2
52 files changed, 976 insertions, 365 deletions
diff --git a/.github/workflows/check_cirrus_cron.yml b/.github/workflows/check_cirrus_cron.yml
index 86f8c26dc..d869576fd 100644
--- a/.github/workflows/check_cirrus_cron.yml
+++ b/.github/workflows/check_cirrus_cron.yml
@@ -6,6 +6,7 @@
name: check_cirrus_cron
on:
+ # Note: This only applies to the master branch.
schedule:
# Assume cirrus cron jobs runs at least once per day
- cron: '59 23 * * *'
@@ -54,6 +55,7 @@ jobs:
echo "# Source: ${{ github.workflow }} workflow on ${{ github.repository }}."
# Separate content from sendgrid.com automatic footer.
echo ""
+ echo ""
) > ./artifacts/email_body.txt
- if: steps.cron.outputs.failures > 0
diff --git a/.golangci.yml b/.golangci.yml
index da22b7602..6e46d55cd 100644
--- a/.golangci.yml
+++ b/.golangci.yml
@@ -4,6 +4,7 @@ run:
deadline: 5m
skip-dirs-use-default: true
skip-dirs:
+ - dependencies
- contrib
- dependencies
- test
@@ -17,6 +18,34 @@ linters:
enable-all: true
disable:
# All these break for one reason or another
+ - nolintlint
+ - gocognit
+ - stylecheck
+ - testpackage
+ - goerr113
+ - exhaustivestruct
+ - errorlint
+ - wrapcheck
+ - paralleltest
+ - wsl
+ - godox
+ - tparallel
+ - gomnd
+ - nlreturn
+ - noctx
+ - nestif
+ - predeclared
+ - thelper
+ - ifshort
+ - staticcheck
+ - forbidigo
+ - exhaustive
+ - whitespace
+ - unparam
+ - gofumpt
+ - gci
+ - godot
+ - makezero
- dupl
- funlen
- gochecknoglobals
diff --git a/Makefile b/Makefile
index f9674afe4..33099fac7 100644
--- a/Makefile
+++ b/Makefile
@@ -619,7 +619,7 @@ endef
.PHONY: .install.golangci-lint
.install.golangci-lint: .gopathok
- VERSION=1.18.0 GOBIN=$(GOBIN) sh ./hack/install_golangci.sh
+ VERSION=1.36.0 GOBIN=$(GOBIN) sh ./hack/install_golangci.sh
.PHONY: .install.bats
.install.bats: .gopathok
diff --git a/README.md b/README.md
index 4dd34d366..8d9c98e81 100644
--- a/README.md
+++ b/README.md
@@ -5,7 +5,7 @@
Podman (the POD MANager) is a tool for managing containers and images, volumes mounted into those containers, and pods made from groups of containers.
Podman is based on libpod, a library for container lifecycle management that is also contained in this repository. The libpod library provides APIs for managing containers, pods, container images, and volumes.
-* [Latest Version: 2.2.1](https://github.com/containers/podman/releases/latest)
+* [Latest Version: 3.0.0](https://github.com/containers/podman/releases/latest)
* Latest Remote client for Windows
* Latest Remote client for MacOs
* Latest Static Remote client for Linux
diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md
index 82ecd741a..17d90aeca 100644
--- a/RELEASE_NOTES.md
+++ b/RELEASE_NOTES.md
@@ -13,7 +13,10 @@
- The `podman container checkpoint` command now supports the `--with-previous` and `--pre-checkpoint` options, and the `podman container restore` command now support the `--import-previous` option. These add support for two-step checkpointing with lowered dump times.
- The `podman push` command can now push manifest lists. Podman will first attempt to push as an image, then fall back to pushing as a manifest list if that fails.
- The `podman generate kube` command can now be run on multiple containers at once, and will generate a single pod containing all of them.
+- The `podman generate kube` and `podman play kube` commands now support Kubernetes DNS configuration, and will preserve custom DNS configuration when exporting or importing YAML ([#9132](https://github.com/containers/podman/issues/9132)).
+- The `podman generate kube` command now properly supports generating YAML for containers and pods creating using host networking (`--net=host`) ([#9077](https://github.com/containers/podman/issues/9077)).
- The `podman kill` command now supports a `--cidfile` option to kill containers given a file containing the container's ID ([#8443](https://github.com/containers/podman/issues/8443)).
+- The `podman pod create` command now supports the `--net=none` option ([#9165](https://github.com/containers/podman/issues/9165)).
- The `podman volume create` command can now specify volume UID and GID as options with the `UID` and `GID` fields passed to the the `--opt` option.
- Initial support has been added for Docker Volume Plugins. Podman can now define available plugins in `containers.conf` and use them to create volumes with `podman volume create --driver`.
- The `podman run` and `podman create` commands now support a new option, `--platform`, to specify the platform of the image to be used when creating the container.
@@ -30,6 +33,10 @@
- The `podman image sign` command can now sign multi-arch images by producing a signature for each image in a given manifest list.
- The `podman image sign` command, when run as rootless, now supports per-user registry configuration files in `$HOME/.config/containers/registries.d`.
- Configuration options for `slirp4netns` can now be set system-wide via the `NetworkCmdOptions` configuration option in `containers.conf`.
+- The MTU of `slirp4netns` can now be configured via the `mtu=` network command option (e.g. `podman run --net slirp4netns:mtu=9000`).
+
+### Security
+- A fix for CVE-2021-20199 is included. Podman between v1.8.0 and v2.2.1 used `127.0.0.1` as the source address for all traffic forwarded into rootless containers by a forwarded port; this has been changed to address the issue.
### Changes
- Shortname aliasing support has now been turned on by default. All Podman commands that must pull an image will, if a TTY is available, prompt the user about what image to pull.
@@ -37,6 +44,7 @@
- The Go bindings for the HTTP API have been rewritten with a focus on limiting dependency footprint and improving extensibility. Read more [here](https://github.com/containers/podman/blob/v3.0/pkg/bindings/README.md).
- The legacy Varlink API has been completely removed from Podman.
- The default log level for Podman has been changed from Error to Warn.
+- The `podman network create` command can now create `macvlan` networks using the `--driver macvlan` option for Docker compatibility. The existing `--macvlan` flag has been deprecated and will be removed in Podman 4.0 some time next year.
- The `podman inspect` command has had the `LogPath` and `LogTag` fields moved into the `LogConfig` structure (from the root of the Inspect structure). The maximum size of the log file is also included.
- The `podman generate systemd` command no longer generates unit files using the deprecated `KillMode=none` option ([#8615](https://github.com/containers/podman/issues/8615)).
- The `podman stop` command now releases the container lock while waiting for it to stop - as such, commands like `podman ps` will no longer block until `podman stop` completes ([#8501](https://github.com/containers/podman/issues/8501)).
@@ -53,6 +61,7 @@
- Fixed a bug where, under some circumstances, container working directories specified by the image (via the `WORKDIR` instruction) but not present in the image, would not be created ([#9040](https://github.com/containers/podman/issues/9040)).
- Fixed a bug where the `podman generate systemd` command would generate invalid unit files if the container was creating using a command line that included doubled braces (`{{` and `}}`), e.g. `--log-opt-tag={{.Name}}` ([#9034](https://github.com/containers/podman/issues/9034)).
- Fixed a bug where the `podman generate systemd --new` command could generate unit files including invalid Podman commands if the container was created using merged short options (e.g. `podman run -dt`) ([#8847](https://github.com/containers/podman/issues/8847)).
+- Fixed a bug where the `podman generate systemd --new` command could generate unit files that did not handle Podman commands including some special characters (e.g. `$`) ([#9176](https://github.com/containers/podman/issues/9176)
- Fixed a bug where rootless containers joining CNI networks could not set a static IP address ([#7842](https://github.com/containers/podman/issues/7842)).
- Fixed a bug where rootless containers joining CNI networks could not set network aliases ([#8567](https://github.com/containers/podman/issues/8567)).
- Fixed a bug where the remote client could, under some circumstances, not include the `Containerfile` when sending build context to the server ([#8374](https://github.com/containers/podman/issues/8374)).
@@ -63,6 +72,8 @@
- Fixed a bug where the `podman play kube` command did not properly print errors that occurred when starting containers.
- Fixed a bug where the `podman play kube` command errored when `hostNetwork` was used ([#8790](https://github.com/containers/podman/issues/8790)).
- Fixed a bug where the `podman play kube` command would always pull images when the `:latest` tag was specified, even if the image was available locally ([#7838](https://github.com/containers/podman/issues/7838)).
+- Fixed a bug where the `podman play kube` command did not properly handle SELinux configuration, rending YAML with custom SELinux configuration unusable ([#8710](https://github.com/containers/podman/issues/8710)).
+- Fixed a bug where the `podman generate kube` command incorrectly populated the `args` and `command` fields of generated YAML ([#9211](https://github.com/containers/podman/issues/9211)).
- Fixed a bug where containers in a pod would create a duplicate entry in the pod's shared `/etc/hosts` file every time the container restarted ([#8921](https://github.com/containers/podman/issues/8921)).
- Fixed a bug where the `podman search --list-tags` command did not support the `--format` option ([#8740](https://github.com/containers/podman/issues/8740)).
- Fixed a bug where the `http_proxy` option in `containers.conf` was not being respected, and instead was set unconditionally to true ([#8843](https://github.com/containers/podman/issues/8843)).
@@ -96,8 +107,19 @@
- Fixed a bug where `--format` did not support JSON output for individual fields ([#8444](https://github.com/containers/podman/issues/8444)).
- Fixed a bug where the `podman stats` command would fail when run on root containers using the `slirp4netns` network mode ([#7883](https://github.com/containers/podman/issues/7883)).
- Fixed a bug where the Podman remote client would ask for a password even if the server's SSH daemon did not support password authentication ([#8498](https://github.com/containers/podman/issues/8498)).
+- Fixed a bug where the `podman stats` command would fail if the system did not support one or more of the cgroup controllers Podman supports ([#8588](https://github.com/containers/podman/issues/8588)).
+- Fixed a bug where the `--mount` option to `podman create` and `podman run` did not ignore the `consistency` mount option.
+- Fixed a bug where failures during the resizing of a container's TTY would print the wrong error.
+- Fixed a bug where the `podman network disconnect` command could cause the `podman inspect` command to fail for a container until it was restarted ([#9234](https://github.com/containers/podman/issues/9234)).
+- Fixed a bug where containers created from a read-only rootfs (using the `--rootfs` option to `podman create` and `podman run`) would fail ([#9230](https://github.com/containers/podman/issues/9230)).
+- Fixed a bug where specifying Go templates to the `--format` option to multiple Podman commands did not support the `join` function ([#8773](https://github.com/containers/podman/issues/8773)).
+- Fixed a bug where the `podman rmi` command could, when run in parallel on multiple images, return `layer not known` errors ([#6510](https://github.com/containers/podman/issues/6510)).
+- Fixed a bug where the `podman inspect` command on containers displayed unlimited ulimits incorrectly ([#9303](https://github.com/containers/podman/issues/9303)).
+- Fixed a bug where Podman would fail to start when a volume was mounted over a directory in a container that contained symlinks that terminated outside the directory and its subdirectories ([#6003](https://github.com/containers/podman/issues/6003)).
### API
+- Libpod API version has been bumped to v3.0.0.
+- All Libpod Pod APIs have been modified to properly report errors with individual containers. Cases where the operation as a whole succeeded but individual containers failed now report an HTTP 409 error ([#8865](https://github.com/containers/podman/issues/8865)).
- The Compat API for Containers now supports the Rename and Copy APIs.
- Fixed a bug where the Compat Prune APIs (for volumes, containers, and images) did not return the amount of space reclaimed in their responses.
- Fixed a bug where the Compat and Libpod Exec APIs for Containers would drop errors that occurred prior to the exec session successfully starting (e.g. a "no such file" error if an invalid executable was passed) ([#8281](https://github.com/containers/podman/issues/8281))
@@ -110,16 +132,19 @@
- Fixed a bug where the Libpod Pull endpoint for Images could fail with an `index out of range` error under certain circumstances ([#8870](https://github.com/containers/podman/issues/8870)).
- Fixed a bug where the Libpod Exists endpoint for Images could panic.
- Fixed a bug where the Compat List API for Containers did not support all filters ([#8860](https://github.com/containers/podman/issues/8860)).
+- Fixed a bug where the Compat List API for Containers did not properly populate the Status field.
- Fixed a bug where the Compat and Libpod Resize APIs for Containers ignored the height and width parameters ([#7102](https://github.com/containers/podman/issues/7102)).
- Fixed a bug where the Compat Search API for Images returned an incorrectly-formatted JSON response ([#8758](https://github.com/containers/podman/pull/8758)).
- Fixed a bug where the Compat Load API for Images did not properly clean up temporary files.
- Fixed a bug where the Compat Create API for Networks could panic when an empty IPAM configuration was specified.
- Fixed a bug where the Compat Inspect and List APIs for Networks did not include Scope.
+- Fixed a bug where the Compat Wait endpoint for Containers did not support the same wait conditions that Docker did.
### Misc
- Updated Buildah to v1.19.2
- Updated the containers/storage library to v1.24.5
-- Updated the containers/common library to v0.33.1
+- Updated the containers/image library to v5.10.2
+- Updated the containers/common library to v0.33.4
## v2.2.1
### Changes
diff --git a/cmd/podman/containers/ps.go b/cmd/podman/containers/ps.go
index 31f44d92f..c9dda4db6 100644
--- a/cmd/podman/containers/ps.go
+++ b/cmd/podman/containers/ps.go
@@ -142,11 +142,19 @@ func checkFlags(c *cobra.Command) error {
}
func jsonOut(responses []entities.ListContainer) error {
- r := make([]entities.ListContainer, 0)
+ type jsonFormat struct {
+ entities.ListContainer
+ Created int64
+ }
+ r := make([]jsonFormat, 0)
for _, con := range responses {
con.CreatedAt = units.HumanDuration(time.Since(con.Created)) + " ago"
con.Status = psReporter{con}.Status()
- r = append(r, con)
+ jf := jsonFormat{
+ ListContainer: con,
+ Created: con.Created.UnixNano(),
+ }
+ r = append(r, jf)
}
b, err := json.MarshalIndent(r, "", " ")
if err != nil {
diff --git a/cmd/podman/secrets/create.go b/cmd/podman/secrets/create.go
index e58ab57cd..ef5d703ca 100644
--- a/cmd/podman/secrets/create.go
+++ b/cmd/podman/secrets/create.go
@@ -16,7 +16,7 @@ import (
var (
createCmd = &cobra.Command{
- Use: "create [options] SECRET FILE|-",
+ Use: "create [options] NAME FILE|-",
Short: "Create a new secret",
Long: "Create a secret. Input can be a path to a file or \"-\" (read from stdin). Default driver is file (unencrypted).",
RunE: create,
diff --git a/contrib/cirrus/cron-fail_addrs.csv b/contrib/cirrus/cron-fail_addrs.csv
index c25fc1226..276158163 100644
--- a/contrib/cirrus/cron-fail_addrs.csv
+++ b/contrib/cirrus/cron-fail_addrs.csv
@@ -1 +1 @@
-rh.container.bot@gmail.com
+rh.container.bot@gmail.com,podman-monitor@lists.podman.io
diff --git a/contrib/spec/podman.spec.in b/contrib/spec/podman.spec.in
index db79ebede..662234f71 100644
--- a/contrib/spec/podman.spec.in
+++ b/contrib/spec/podman.spec.in
@@ -380,6 +380,29 @@ tar zxf %{SOURCE1}
%build
mkdir _build
pushd _build
+
+# These flags should work for all rpm distros and arches
+export CGO_CFLAGS="-O2 -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -ffat-lto-objects -fexceptions -fasynchronous-unwind-tables -fstack-protector-strong -fstack-clash-protection -D_GNU_SOURCE -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE"
+
+%if 0%{?fedora} || 0%{?rhel}
+# This flag is only present on RH-family distros
+export CGO_CFLAGS+=" -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1"
+%endif
+
+%ifnarch %{ix86}
+# Build fails on i686 with this flag
+export CGO_CFLAGS+=" -D_FILE_OFFSET_BITS=64"
+%endif
+
+%ifarch x86_64
+# Builds only on x86_64 with this flag
+export CGO_CFLAGS+=" -m64 -mtune=generic"
+%if 0%{?fedora} || 0%{?rhel} >= 8
+# Build fails on rhel7 and non-86_64 with this flag
+export CGO_CFLAGS+=" -fcf-protection"
+%endif
+%endif
+
mkdir -p src/%{provider}.%{provider_tld}/%{project}
ln -s ../../../../ src/%{import_path}
popd
diff --git a/dependencies/dependencies.go b/dependencies/dependencies.go
index b03ab149b..b1b0aee08 100644
--- a/dependencies/dependencies.go
+++ b/dependencies/dependencies.go
@@ -1,3 +1,5 @@
+// +build !linter
+
package dependencies
import (
diff --git a/go.mod b/go.mod
index 08a240e52..1f494ef95 100644
--- a/go.mod
+++ b/go.mod
@@ -52,7 +52,7 @@ require (
github.com/pmezard/go-difflib v1.0.0
github.com/rootless-containers/rootlesskit v0.13.0
github.com/sirupsen/logrus v1.7.0
- github.com/spf13/cobra v1.1.1
+ github.com/spf13/cobra v1.1.2
github.com/spf13/pflag v1.0.5
github.com/stretchr/testify v1.7.0
github.com/syndtr/gocapability v0.0.0-20180916011248-d98352740cb2
diff --git a/go.sum b/go.sum
index 7ebb916d5..43d37a098 100644
--- a/go.sum
+++ b/go.sum
@@ -558,6 +558,8 @@ github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkU
github.com/spf13/cobra v0.0.2-0.20171109065643-2da4a54c5cee/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ=
github.com/spf13/cobra v1.1.1 h1:KfztREH0tPxJJ+geloSLaAkaPkr4ki2Er5quFV1TDo4=
github.com/spf13/cobra v1.1.1/go.mod h1:WnodtKOvamDL/PwE2M4iKs8aMDBZ5Q5klgD3qfVJQMI=
+github.com/spf13/cobra v1.1.2 h1:frHO75w/dH7kEc+e2KYZZKY4+PLrp39OqI77oB8m0KQ=
+github.com/spf13/cobra v1.1.2/go.mod h1:ZjwqWkCg0LnXvLRIfTLdB4Y/MCO3gMHHJ2KFxQZy4xE=
github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
github.com/spf13/pflag v0.0.0-20170130214245-9ff6c6923cff/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/spf13/pflag v1.0.1-0.20171106142849-4c012f6dcd95/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
@@ -895,6 +897,8 @@ gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
+gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
+gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776 h1:tQIYjPdBoyREyB9XMu+nnTclpTYkz2zFM+lzLJFO4gQ=
gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/hack/golangci-lint.sh b/hack/golangci-lint.sh
index 5be750129..bcb83a2fd 100755
--- a/hack/golangci-lint.sh
+++ b/hack/golangci-lint.sh
@@ -5,7 +5,7 @@ set -e
declare -A BUILD_TAGS
# TODO: add systemd tag
-BUILD_TAGS[default]="apparmor,seccomp,selinux"
+BUILD_TAGS[default]="apparmor,seccomp,selinux,linter"
BUILD_TAGS[abi]="${BUILD_TAGS[default]},!remoteclient"
BUILD_TAGS[tunnel]="${BUILD_TAGS[default]},remote,remoteclient"
diff --git a/libpod/container_inspect.go b/libpod/container_inspect.go
index f50c7dbfe..efe09af92 100644
--- a/libpod/container_inspect.go
+++ b/libpod/container_inspect.go
@@ -871,8 +871,8 @@ func (c *Container) generateInspectContainerHostConfig(ctrSpec *spec.Spec, named
for _, limit := range ctrSpec.Process.Rlimits {
newLimit := define.InspectUlimit{}
newLimit.Name = limit.Type
- newLimit.Soft = limit.Soft
- newLimit.Hard = limit.Hard
+ newLimit.Soft = int64(limit.Soft)
+ newLimit.Hard = int64(limit.Hard)
hostConfig.Ulimits = append(hostConfig.Ulimits, newLimit)
}
}
diff --git a/libpod/container_internal.go b/libpod/container_internal.go
index b280e79d1..9ea9e02cd 100644
--- a/libpod/container_internal.go
+++ b/libpod/container_internal.go
@@ -13,6 +13,7 @@ import (
"strings"
"time"
+ "github.com/containers/buildah/copier"
"github.com/containers/common/pkg/secrets"
"github.com/containers/podman/v2/libpod/define"
"github.com/containers/podman/v2/libpod/events"
@@ -1582,18 +1583,8 @@ func (c *Container) mountNamedVolume(v *ContainerNamedVolume, mountpoint string)
return nil, err
}
- // HACK HACK HACK - copy up into a volume driver is 100% broken
- // right now.
- if vol.UsesVolumeDriver() {
- logrus.Infof("Not copying up into volume %s as it uses a volume driver", vol.Name())
- return vol, nil
- }
-
// If the volume is not empty, we should not copy up.
- volMount, err := vol.MountPoint()
- if err != nil {
- return nil, err
- }
+ volMount := vol.mountPoint()
contents, err := ioutil.ReadDir(volMount)
if err != nil {
return nil, errors.Wrapf(err, "error listing contents of volume %s mountpoint when copying up from container %s", vol.Name(), c.ID())
@@ -1609,8 +1600,55 @@ func (c *Container) mountNamedVolume(v *ContainerNamedVolume, mountpoint string)
if err != nil {
return nil, errors.Wrapf(err, "error calculating destination path to copy up container %s volume %s", c.ID(), vol.Name())
}
- if err := c.copyWithTarFromImage(srcDir, volMount); err != nil && !os.IsNotExist(err) {
- return nil, errors.Wrapf(err, "error copying content from container %s into volume %s", c.ID(), vol.Name())
+ // Do a manual stat on the source directory to verify existence.
+ // Skip the rest if it exists.
+ // TODO: Should this be stat or lstat? I'm using lstat because I
+ // think copy-up doesn't happen when the source is a link.
+ srcStat, err := os.Lstat(srcDir)
+ if err != nil {
+ if os.IsNotExist(err) {
+ // Source does not exist, don't bother copying
+ // up.
+ return vol, nil
+ }
+ return nil, errors.Wrapf(err, "error identifying source directory for copy up into volume %s", vol.Name())
+ }
+ // If it's not a directory we're mounting over it.
+ if !srcStat.IsDir() {
+ return vol, nil
+ }
+
+ // Buildah Copier accepts a reader, so we'll need a pipe.
+ reader, writer := io.Pipe()
+ defer reader.Close()
+
+ errChan := make(chan error, 1)
+
+ logrus.Infof("About to copy up into volume %s", vol.Name())
+
+ // Copy, container side: get a tar archive of what needs to be
+ // streamed into the volume.
+ go func() {
+ defer writer.Close()
+ getOptions := copier.GetOptions{
+ KeepDirectoryNames: false,
+ }
+ errChan <- copier.Get(mountpoint, "", getOptions, []string{v.Dest + "/."}, writer)
+ }()
+
+ // Copy, volume side: stream what we've written to the pipe, into
+ // the volume.
+ copyOpts := copier.PutOptions{}
+ if err := copier.Put(volMount, "", copyOpts, reader); err != nil {
+ err2 := <-errChan
+ if err2 != nil {
+ logrus.Errorf("Error streaming contents of container %s directory for volume copy-up: %v", c.ID(), err2)
+ }
+ return nil, errors.Wrapf(err, "error copying up to volume %s", vol.Name())
+ }
+
+ if err := <-errChan; err != nil {
+ return nil, errors.Wrapf(err, "error streaming container content for copy up into volume %s", vol.Name())
}
}
return vol, nil
@@ -2060,17 +2098,6 @@ func (c *Container) unmount(force bool) error {
return nil
}
-// this should be from chrootarchive.
-// Container MUST be mounted before calling.
-func (c *Container) copyWithTarFromImage(source, dest string) error {
- mappings := idtools.NewIDMappingsFromMaps(c.config.IDMappings.UIDMap, c.config.IDMappings.GIDMap)
- a := archive.NewArchiver(mappings)
- if err := c.copyOwnerAndPerms(source, dest); err != nil {
- return err
- }
- return a.CopyWithTar(source, dest)
-}
-
// checkReadyForRemoval checks whether the given container is ready to be
// removed.
// These checks are only used if force-remove is not specified.
diff --git a/libpod/container_internal_linux.go b/libpod/container_internal_linux.go
index 3583f8fdd..1c4537a27 100644
--- a/libpod/container_internal_linux.go
+++ b/libpod/container_internal_linux.go
@@ -2278,23 +2278,6 @@ func (c *Container) generatePasswdAndGroup() (string, string, error) {
return passwdPath, groupPath, nil
}
-func (c *Container) copyOwnerAndPerms(source, dest string) error {
- info, err := os.Stat(source)
- if err != nil {
- if os.IsNotExist(err) {
- return nil
- }
- return err
- }
- if err := os.Chmod(dest, info.Mode()); err != nil {
- return err
- }
- if err := os.Chown(dest, int(info.Sys().(*syscall.Stat_t).Uid), int(info.Sys().(*syscall.Stat_t).Gid)); err != nil {
- return err
- }
- return nil
-}
-
// Get cgroup path in a format suitable for the OCI spec
func (c *Container) getOCICgroupPath() (string, error) {
unified, err := cgroups.IsCgroup2UnifiedMode()
diff --git a/libpod/define/container_inspect.go b/libpod/define/container_inspect.go
index 2cdd53cbc..0f355d20a 100644
--- a/libpod/define/container_inspect.go
+++ b/libpod/define/container_inspect.go
@@ -122,9 +122,9 @@ type InspectUlimit struct {
// Name is the name (type) of the ulimit.
Name string `json:"Name"`
// Soft is the soft limit that will be applied.
- Soft uint64 `json:"Soft"`
+ Soft int64 `json:"Soft"`
// Hard is the hard limit that will be applied.
- Hard uint64 `json:"Hard"`
+ Hard int64 `json:"Hard"`
}
// InspectDevice is a single device that will be mounted into the container.
diff --git a/libpod/volume.go b/libpod/volume.go
index 4c137cb8e..5cc5e7e40 100644
--- a/libpod/volume.go
+++ b/libpod/volume.go
@@ -130,11 +130,18 @@ func (v *Volume) MountPoint() (string, error) {
if err := v.update(); err != nil {
return "", err
}
+ }
+
+ return v.mountPoint(), nil
+}
- return v.state.MountPoint, nil
+// Internal-only helper for volume mountpoint
+func (v *Volume) mountPoint() string {
+ if v.UsesVolumeDriver() {
+ return v.state.MountPoint
}
- return v.config.MountPoint, nil
+ return v.config.MountPoint
}
// Options return the volume's options
diff --git a/pkg/api/handlers/compat/images_push.go b/pkg/api/handlers/compat/images_push.go
index 34b53f34e..77d891546 100644
--- a/pkg/api/handlers/compat/images_push.go
+++ b/pkg/api/handlers/compat/images_push.go
@@ -1,6 +1,8 @@
package compat
import (
+ "fmt"
+ "io/ioutil"
"net/http"
"strings"
@@ -19,6 +21,14 @@ import (
func PushImage(w http.ResponseWriter, r *http.Request) {
decoder := r.Context().Value("decoder").(*schema.Decoder)
runtime := r.Context().Value("runtime").(*libpod.Runtime)
+
+ digestFile, err := ioutil.TempFile("", "digest.txt")
+ if err != nil {
+ utils.Error(w, "unable to create digest tempfile", http.StatusInternalServerError, errors.Wrap(err, "unable to create tempfile"))
+ return
+ }
+ defer digestFile.Close()
+
// Now use the ABI implementation to prevent us from having duplicate
// code.
imageEngine := abi.ImageEngine{Libpod: runtime}
@@ -65,12 +75,13 @@ func PushImage(w http.ResponseWriter, r *http.Request) {
password = authconf.Password
}
options := entities.ImagePushOptions{
- All: query.All,
- Authfile: authfile,
- Compress: query.Compress,
- Format: query.Format,
- Password: password,
- Username: username,
+ All: query.All,
+ Authfile: authfile,
+ Compress: query.Compress,
+ Format: query.Format,
+ Password: password,
+ Username: username,
+ DigestFile: digestFile.Name(),
}
if _, found := r.URL.Query()["tlsVerify"]; found {
options.SkipTLSVerify = types.NewOptionalBool(!query.TLSVerify)
@@ -93,5 +104,21 @@ func PushImage(w http.ResponseWriter, r *http.Request) {
return
}
- utils.WriteResponse(w, http.StatusOK, "")
+ digestBytes, err := ioutil.ReadAll(digestFile)
+ if err != nil {
+ utils.Error(w, "Something went wrong.", http.StatusInternalServerError, errors.Wrap(err, "failed to read digest tmp file"))
+ return
+ }
+
+ tag := query.Tag
+ if tag == "" {
+ tag = "latest"
+ }
+ respData := struct {
+ Status string `json:"status"`
+ }{
+ Status: fmt.Sprintf("%s: digest: %s size: null", tag, string(digestBytes)),
+ }
+
+ utils.WriteJSON(w, http.StatusOK, &respData)
}
diff --git a/pkg/api/handlers/compat/networks.go b/pkg/api/handlers/compat/networks.go
index 85d2db87e..83c80aac9 100644
--- a/pkg/api/handlers/compat/networks.go
+++ b/pkg/api/handlers/compat/networks.go
@@ -400,6 +400,9 @@ func Prune(w http.ResponseWriter, r *http.Request) {
utils.Error(w, "Something went wrong.", http.StatusInternalServerError, err)
return
}
+ type response struct {
+ NetworksDeleted []string
+ }
var prunedNetworks []string //nolint
for _, pr := range pruneReports {
if pr.Error != nil {
@@ -408,5 +411,5 @@ func Prune(w http.ResponseWriter, r *http.Request) {
}
prunedNetworks = append(prunedNetworks, pr.Name)
}
- utils.WriteResponse(w, http.StatusOK, prunedNetworks)
+ utils.WriteResponse(w, http.StatusOK, response{NetworksDeleted: prunedNetworks})
}
diff --git a/pkg/domain/infra/abi/manifest.go b/pkg/domain/infra/abi/manifest.go
index 626f1f7bf..da7482407 100644
--- a/pkg/domain/infra/abi/manifest.go
+++ b/pkg/domain/infra/abi/manifest.go
@@ -1,5 +1,3 @@
-// +build !remote
-
package abi
import (
diff --git a/test/apiv2/12-imagesMore.at b/test/apiv2/12-imagesMore.at
index fe6a271ce..4f3ddf925 100644
--- a/test/apiv2/12-imagesMore.at
+++ b/test/apiv2/12-imagesMore.at
@@ -3,6 +3,9 @@
# Tests for more image-related endpoints
#
+red='\e[31m'
+nc='\e[0m'
+
podman pull -q $IMAGE
t GET libpod/images/json 200 \
@@ -26,6 +29,17 @@ t GET libpod/images/$IMAGE/json 200 \
podman run -d --name registry -p 5000:5000 quay.io/libpod/registry:2.6 /entrypoint.sh /etc/docker/registry/config.yml
wait_for_port localhost 5000
+# Push to local registry and check output
+while read -r LINE
+do
+ if echo "${LINE}" | jq --exit-status 'select( .status != null) | select ( .status | contains("digest: sha256:"))' &>/dev/null; then
+ GOT_DIGEST="1"
+ fi
+done < <(curl -sL "http://$HOST:$PORT/images/localhost:5000/myrepo/push?tlsVerify=false&tag=mytag" -XPOST)
+if [ -z "${GOT_DIGEST}" ] ; then
+ echo -e "${red}not ok: did not found digest in output${nc}" 1>&2;
+fi
+
# Push to local registry
t POST "images/localhost:5000/myrepo/push?tlsVerify=false&tag=mytag" '' 200
@@ -43,3 +57,7 @@ t DELETE libpod/images/$IMAGE 200 \
.ExitCode=0
t DELETE libpod/images/quay.io/libpod/registry:2.6 200 \
.ExitCode=0
+
+if [ -z "${GOT_DIGEST}" ] ; then
+ exit 1;
+fi
diff --git a/test/apiv2/rest_api/test_rest_v2_0_0.py b/test/apiv2/rest_api/test_rest_v2_0_0.py
index 73db35cc1..05c24f2ea 100644
--- a/test/apiv2/rest_api/test_rest_v2_0_0.py
+++ b/test/apiv2/rest_api/test_rest_v2_0_0.py
@@ -483,8 +483,16 @@ class TestApi(unittest.TestCase):
inspect = requests.get(PODMAN_URL + f"/v1.40/networks/{ident}")
self.assertEqual(inspect.status_code, 404, inspect.content)
+ # network prune
+ prune_name = "Network_" + "".join(random.choice(string.ascii_letters) for i in range(10))
+ prune_create = requests.post(PODMAN_URL + "/v1.40/networks/create", json={"Name": prune_name})
+ self.assertEqual(create.status_code, 201, prune_create.content)
+
prune = requests.post(PODMAN_URL + "/v1.40/networks/prune")
self.assertEqual(prune.status_code, 200, prune.content)
+ obj = json.loads(prune.content)
+ self.assertTrue(prune_name in obj["NetworksDeleted"])
+
def test_volumes_compat(self):
name = "Volume_" + "".join(random.choice(string.ascii_letters) for i in range(10))
diff --git a/test/e2e/inspect_test.go b/test/e2e/inspect_test.go
index 8fc9721f9..12bc886a8 100644
--- a/test/e2e/inspect_test.go
+++ b/test/e2e/inspect_test.go
@@ -466,4 +466,28 @@ var _ = Describe("Podman inspect", func() {
Expect(len(inspect)).To(Equal(1))
Expect(len(inspect[0].NetworkSettings.Networks)).To(Equal(1))
})
+
+ It("Container inspect with unlimited uilimits should be -1", func() {
+ ctrName := "testctr"
+ session := podmanTest.Podman([]string{"run", "-d", "--ulimit", "core=-1:-1", "--name", ctrName, ALPINE, "top"})
+ session.WaitWithDefaultTimeout()
+ Expect(session.ExitCode()).To(BeZero())
+
+ inspect := podmanTest.Podman([]string{"inspect", ctrName})
+ inspect.WaitWithDefaultTimeout()
+ Expect(inspect.ExitCode()).To(BeZero())
+
+ data := inspect.InspectContainerToJSON()
+ ulimits := data[0].HostConfig.Ulimits
+ Expect(len(ulimits)).To(BeNumerically(">", 0))
+ found := false
+ for _, ulimit := range ulimits {
+ if ulimit.Name == "RLIMIT_CORE" {
+ found = true
+ Expect(ulimit.Soft).To(BeNumerically("==", -1))
+ Expect(ulimit.Hard).To(BeNumerically("==", -1))
+ }
+ }
+ Expect(found).To(BeTrue())
+ })
})
diff --git a/test/e2e/ps_test.go b/test/e2e/ps_test.go
index db3f7a36b..225bd538e 100644
--- a/test/e2e/ps_test.go
+++ b/test/e2e/ps_test.go
@@ -5,6 +5,7 @@ import (
"os"
"regexp"
"sort"
+ "strconv"
"strings"
. "github.com/containers/podman/v2/test/utils"
@@ -210,6 +211,22 @@ var _ = Describe("Podman ps", func() {
Expect(result.IsJSONOutputValid()).To(BeTrue())
})
+ It("podman ps json format Created field is int64", func() {
+ session := podmanTest.RunTopContainer("test1")
+ session.WaitWithDefaultTimeout()
+ Expect(session.ExitCode()).To(Equal(0))
+
+ result := podmanTest.Podman([]string{"ps", "--format", "json"})
+ result.WaitWithDefaultTimeout()
+ Expect(result.ExitCode()).To(Equal(0))
+
+ // Make sure Created field is an int64
+ created, err := result.jq(".[0].Created")
+ Expect(err).To(BeNil())
+ _, err = strconv.ParseInt(created, 10, 64)
+ Expect(err).To(BeNil())
+ })
+
It("podman ps print a human-readable `Status` with json format", func() {
_, ec, _ := podmanTest.RunLsContainer("test1")
Expect(ec).To(Equal(0))
diff --git a/test/e2e/run_volume_test.go b/test/e2e/run_volume_test.go
index bc89b59de..19d82c974 100644
--- a/test/e2e/run_volume_test.go
+++ b/test/e2e/run_volume_test.go
@@ -304,6 +304,24 @@ var _ = Describe("Podman run with volumes", func() {
Expect(separateVolumeSession.OutputToString()).To(Equal(baselineOutput))
})
+ It("podman named volume copyup symlink", func() {
+ imgName := "testimg"
+ dockerfile := `FROM alpine
+RUN touch /testfile
+RUN sh -c "cd /etc/apk && ln -s ../../testfile"`
+ podmanTest.BuildImage(dockerfile, imgName, "false")
+
+ baselineSession := podmanTest.Podman([]string{"run", "--rm", "-t", "-i", imgName, "ls", "/etc/apk/"})
+ baselineSession.WaitWithDefaultTimeout()
+ Expect(baselineSession.ExitCode()).To(Equal(0))
+ baselineOutput := baselineSession.OutputToString()
+
+ outputSession := podmanTest.Podman([]string{"run", "-t", "-i", "-v", "/etc/apk/", imgName, "ls", "/etc/apk/"})
+ outputSession.WaitWithDefaultTimeout()
+ Expect(outputSession.ExitCode()).To(Equal(0))
+ Expect(outputSession.OutputToString()).To(Equal(baselineOutput))
+ })
+
It("podman read-only tmpfs conflict with volume", func() {
session := podmanTest.Podman([]string{"run", "--rm", "-t", "-i", "--read-only", "-v", "tmp_volume:" + dest, ALPINE, "touch", dest + "/a"})
session.WaitWithDefaultTimeout()
diff --git a/test/system/600-completion.bats b/test/system/600-completion.bats
index 8cac2c9aa..fbb0da231 100644
--- a/test/system/600-completion.bats
+++ b/test/system/600-completion.bats
@@ -157,7 +157,17 @@ function check_shell_completion() {
# resume
;;&
- *PATH* | *CONTEXT* | *KUBEFILE* | *COMMAND* | *ARG...* | *URI*)
+ *SECRET*)
+ run_completion "$@" $cmd "${extra_args[@]}" ""
+ is "$output" ".*$random_secret_name${nl}" \
+ "$* $cmd: actual secret listed in suggestions"
+ _check_completion_end NoFileComp
+
+ match=true
+ # resume
+ ;;&
+
+ *PATH* | *CONTEXT* | *FILE* | *COMMAND* | *ARG...* | *URI*)
# default shell completion should be done for everything which accepts a path
run_completion "$@" $cmd "${extra_args[@]}" ""
@@ -232,6 +242,11 @@ function _check_completion_end() {
random_image_tag=$(random_string 5)
random_network_name=$(random_string 30)
random_volume_name=$(random_string 30)
+ random_secret_name=$(random_string 30)
+ random_secret_content=$(random_string 30)
+ secret_file=$PODMAN_TMPDIR/$(random_string 10)
+
+ echo $random_secret_content > $secret_file
# create a container for each state since some commands are only suggesting running container for example
run_podman create --name created-$random_container_name $IMAGE
@@ -263,6 +278,8 @@ function _check_completion_end() {
# create volume
run_podman volume create $random_volume_name
+ # create secret
+ run_podman secret create $random_secret_name $secret_file
# $PODMAN may be a space-separated string, e.g. if we include a --url.
local -a podman_as_array=($PODMAN)
@@ -274,6 +291,9 @@ function _check_completion_end() {
check_shell_completion
# cleanup
+ run_podman secret rm $random_secret_name
+ rm -f $secret_file
+
run_podman volume rm $random_volume_name
run_podman network rm $random_network_name
diff --git a/vendor/github.com/spf13/cobra/.golangci.yml b/vendor/github.com/spf13/cobra/.golangci.yml
new file mode 100644
index 000000000..0d6e61793
--- /dev/null
+++ b/vendor/github.com/spf13/cobra/.golangci.yml
@@ -0,0 +1,48 @@
+run:
+ deadline: 5m
+
+linters:
+ disable-all: true
+ enable:
+ #- bodyclose
+ - deadcode
+ #- depguard
+ #- dogsled
+ #- dupl
+ - errcheck
+ #- exhaustive
+ #- funlen
+ - gas
+ #- gochecknoinits
+ - goconst
+ #- gocritic
+ #- gocyclo
+ #- gofmt
+ - goimports
+ - golint
+ #- gomnd
+ #- goprintffuncname
+ #- gosec
+ #- gosimple
+ - govet
+ - ineffassign
+ - interfacer
+ #- lll
+ - maligned
+ - megacheck
+ #- misspell
+ #- nakedret
+ #- noctx
+ #- nolintlint
+ #- rowserrcheck
+ #- scopelint
+ #- staticcheck
+ - structcheck
+ #- stylecheck
+ #- typecheck
+ - unconvert
+ #- unparam
+ #- unused
+ - varcheck
+ #- whitespace
+ fast: false
diff --git a/vendor/github.com/spf13/cobra/.travis.yml b/vendor/github.com/spf13/cobra/.travis.yml
index a9bd4e547..0821efdca 100644
--- a/vendor/github.com/spf13/cobra/.travis.yml
+++ b/vendor/github.com/spf13/cobra/.travis.yml
@@ -1,29 +1,28 @@
language: go
stages:
- - diff
- test
- build
go:
- - 1.12.x
- - 1.13.x
+ - 1.14.x
+ - 1.15.x
- tip
+env: GO111MODULE=on
+
before_install:
- go get -u github.com/kyoh86/richgo
- go get -u github.com/mitchellh/gox
+ - curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin latest
matrix:
allow_failures:
- go: tip
include:
- - stage: diff
- go: 1.13.x
- script: make fmt
- stage: build
- go: 1.13.x
+ go: 1.14.x
script: make cobra_generator
-script:
+script:
- make test
diff --git a/vendor/github.com/spf13/cobra/CHANGELOG.md b/vendor/github.com/spf13/cobra/CHANGELOG.md
index 742d6d6e2..648c8f490 100644
--- a/vendor/github.com/spf13/cobra/CHANGELOG.md
+++ b/vendor/github.com/spf13/cobra/CHANGELOG.md
@@ -1,11 +1,36 @@
# Cobra Changelog
-## Pending
-* Fix man page doc generation - no auto generated tag when `cmd.DisableAutoGenTag = true` @jpmcb
+## v1.1.2
+
+### Notable Changes
+
+* Bump license year to 2021 in golden files (#1309) @Bowbaq
+* Enhance PowerShell completion with custom comp (#1208) @Luap99
+* Update gopkg.in/yaml.v2 to v2.4.0: The previous breaking change in yaml.v2 v2.3.0 has been reverted, see go-yaml/yaml#670
+* Documentation readability improvements (#1228 etc.) @zaataylor etc.
+* Use golangci-lint: Repair warnings and errors resulting from linting (#1044) @umarcor
+
+## v1.1.1
+
+* **Fix:** yaml.v2 2.3.0 contained a unintended breaking change. This release reverts to yaml.v2 v2.2.8 which has recent critical CVE fixes, but does not have the breaking changes. See https://github.com/spf13/cobra/pull/1259 for context.
+* **Fix:** correct internal formatting for go-md2man v2 (which caused man page generation to be broken). See https://github.com/spf13/cobra/issues/1049 for context.
+
+## v1.1.0
+
+### Notable Changes
+
+* Extend Go completions and revamp zsh comp (#1070)
+* Fix man page doc generation - no auto generated tag when `cmd.DisableAutoGenTag = true` (#1104) @jpmcb
+* Add completion for help command (#1136)
+* Complete subcommands when TraverseChildren is set (#1171)
+* Fix stderr printing functions (#894)
+* fix: fish output redirection (#1247)
## v1.0.0
+
Announcing v1.0.0 of Cobra. 🎉
-**Notable Changes**
+
+### Notable Changes
* Fish completion (including support for Go custom completion) @marckhouzam
* API (urgent): Rename BashCompDirectives to ShellCompDirectives @marckhouzam
* Remove/replace SetOutput on Command - deprecated @jpmcb
diff --git a/vendor/github.com/spf13/cobra/CONDUCT.md b/vendor/github.com/spf13/cobra/CONDUCT.md
new file mode 100644
index 000000000..9d16f88fd
--- /dev/null
+++ b/vendor/github.com/spf13/cobra/CONDUCT.md
@@ -0,0 +1,37 @@
+## Cobra User Contract
+
+### Versioning
+Cobra will follow a steady release cadence. Non breaking changes will be released as minor versions quarterly. Patch bug releases are at the discretion of the maintainers. Users can expect security patch fixes to be released within relatively short order of a CVE becoming known. For more information on security patch fixes see the CVE section below. Releases will follow [Semantic Versioning](https://semver.org/). Users tracking the Master branch should expect unpredictable breaking changes as the project continues to move forward. For stability, it is highly recommended to use a release.
+
+### Backward Compatibility
+We will maintain two major releases in a moving window. The N-1 release will only receive bug fixes and security updates and will be dropped once N+1 is released.
+
+### Deprecation
+Deprecation of Go versions or dependent packages will only occur in major releases. To reduce the change of this taking users by surprise, any large deprecation will be preceded by an announcement in the [#cobra slack channel](https://gophers.slack.com/archives/CD3LP1199) and an Issue on Github.
+
+### CVE
+Maintainers will make every effort to release security patches in the case of a medium to high severity CVE directly impacting the library. The speed in which these patches reach a release is up to the discretion of the maintainers. A low severity CVE may be a lower priority than a high severity one.
+
+### Communication
+Cobra maintainers will use GitHub issues and the [#cobra slack channel](https://gophers.slack.com/archives/CD3LP1199) as the primary means of communication with the community. This is to foster open communication with all users and contributors.
+
+### Breaking Changes
+Breaking changes are generally allowed in the master branch, as this is the branch used to develop the next release of Cobra.
+
+There may be times, however, when master is closed for breaking changes. This is likely to happen as we near the release of a new version.
+
+Breaking changes are not allowed in release branches, as these represent minor versions that have already been released. These version have consumers who expect the APIs, behaviors, etc, to remain stable during the lifetime of the patch stream for the minor release.
+
+Examples of breaking changes include:
+- Removing or renaming exported constant, variable, type, or function.
+- Updating the version of critical libraries such as `spf13/pflag`, `spf13/viper` etc...
+ - Some version updates may be acceptable for picking up bug fixes, but maintainers must exercise caution when reviewing.
+
+There may, at times, need to be exceptions where breaking changes are allowed in release branches. These are at the discretion of the project's maintainers, and must be carefully considered before merging.
+
+### CI Testing
+Maintainers will ensure the Cobra test suite utilizes the current supported versions of Golang.
+
+### Disclaimer
+Changes to this document and the contents therein are at the discretion of the maintainers.
+None of the contents of this document are legally binding in any way to the maintainers or the users.
diff --git a/vendor/github.com/spf13/cobra/Makefile b/vendor/github.com/spf13/cobra/Makefile
index e9740d1e1..472c73bf1 100644
--- a/vendor/github.com/spf13/cobra/Makefile
+++ b/vendor/github.com/spf13/cobra/Makefile
@@ -1,21 +1,29 @@
BIN="./bin"
SRC=$(shell find . -name "*.go")
+ifeq (, $(shell which golangci-lint))
+$(warning "could not find golangci-lint in $(PATH), run: curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh")
+endif
+
ifeq (, $(shell which richgo))
$(warning "could not find richgo in $(PATH), run: go get github.com/kyoh86/richgo")
endif
-.PHONY: fmt vet test cobra_generator install_deps clean
+.PHONY: fmt lint test cobra_generator install_deps clean
default: all
-all: fmt vet test cobra_generator
+all: fmt test cobra_generator
fmt:
$(info ******************** checking formatting ********************)
@test -z $(shell gofmt -l $(SRC)) || (gofmt -d $(SRC); exit 1)
-test: install_deps vet
+lint:
+ $(info ******************** running lint tools ********************)
+ golangci-lint run -v
+
+test: install_deps lint
$(info ******************** running tests ********************)
richgo test -v ./...
@@ -28,9 +36,5 @@ install_deps:
$(info ******************** downloading dependencies ********************)
go get -v ./...
-vet:
- $(info ******************** vetting ********************)
- go vet ./...
-
clean:
rm -rf $(BIN)
diff --git a/vendor/github.com/spf13/cobra/README.md b/vendor/github.com/spf13/cobra/README.md
index 3cf1b25d8..a1b13ddda 100644
--- a/vendor/github.com/spf13/cobra/README.md
+++ b/vendor/github.com/spf13/cobra/README.md
@@ -6,6 +6,7 @@ Cobra is used in many Go projects such as [Kubernetes](http://kubernetes.io/),
[Hugo](https://gohugo.io), and [Github CLI](https://github.com/cli/cli) to
name a few. [This list](./projects_using_cobra.md) contains a more extensive list of projects using Cobra.
+[![](https://img.shields.io/github/workflow/status/spf13/cobra/Test?longCache=tru&label=Test&logo=github%20actions&logoColor=fff)](https://github.com/spf13/cobra/actions?query=workflow%3ATest)
[![Build Status](https://travis-ci.org/spf13/cobra.svg "Travis CI status")](https://travis-ci.org/spf13/cobra)
[![GoDoc](https://godoc.org/github.com/spf13/cobra?status.svg)](https://godoc.org/github.com/spf13/cobra)
[![Go Report Card](https://goreportcard.com/badge/github.com/spf13/cobra)](https://goreportcard.com/report/github.com/spf13/cobra)
@@ -62,8 +63,8 @@ Cobra is built on a structure of commands, arguments & flags.
**Commands** represent actions, **Args** are things and **Flags** are modifiers for those actions.
-The best applications will read like sentences when used. Users will know how
-to use the application because they will natively understand how to use it.
+The best applications read like sentences when used, and as a result, users
+intuitively know how to interact with them.
The pattern to follow is
`APPNAME VERB NOUN --ADJECTIVE.`
@@ -234,11 +235,6 @@ func init() {
rootCmd.AddCommand(initCmd)
}
-func er(msg interface{}) {
- fmt.Println("Error:", msg)
- os.Exit(1)
-}
-
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
@@ -246,9 +242,7 @@ func initConfig() {
} else {
// Find home directory.
home, err := homedir.Dir()
- if err != nil {
- er(err)
- }
+ cobra.CheckErr(err)
// Search config in home directory with name ".cobra" (without extension).
viper.AddConfigPath(home)
@@ -268,7 +262,7 @@ func initConfig() {
With the root command you need to have your main function execute it.
Execute should be run on the root for clarity, though it can be called on any command.
-In a Cobra app, typically the main.go file is very bare. It serves, one purpose, to initialize Cobra.
+In a Cobra app, typically the main.go file is very bare. It serves one purpose: to initialize Cobra.
```go
package main
@@ -363,7 +357,7 @@ There are two different approaches to assign a flag.
### Persistent Flags
-A flag can be 'persistent' meaning that this flag will be available to the
+A flag can be 'persistent', meaning that this flag will be available to the
command it's assigned to as well as every command under that command. For
global flags, assign a flag as a persistent flag on the root.
@@ -373,7 +367,7 @@ rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose out
### Local Flags
-A flag can also be assigned locally which will only apply to that specific command.
+A flag can also be assigned locally, which will only apply to that specific command.
```go
localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
@@ -381,8 +375,8 @@ localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to rea
### Local Flag on Parent Commands
-By default Cobra only parses local flags on the target command, any local flags on
-parent commands are ignored. By enabling `Command.TraverseChildren` Cobra will
+By default, Cobra only parses local flags on the target command, and any local flags on
+parent commands are ignored. By enabling `Command.TraverseChildren`, Cobra will
parse local flags on each command before executing the target command.
```go
@@ -404,8 +398,8 @@ func init() {
}
```
-In this example the persistent flag `author` is bound with `viper`.
-**Note**, that the variable `author` will not be set to the value from config,
+In this example, the persistent flag `author` is bound with `viper`.
+**Note**: the variable `author` will not be set to the value from config,
when the `--author` flag is not provided by user.
More in [viper documentation](https://github.com/spf13/viper#working-with-flags).
@@ -465,7 +459,7 @@ var cmd = &cobra.Command{
In the example below, we have defined three commands. Two are at the top level
and one (cmdTimes) is a child of one of the top commands. In this case the root
-is not executable meaning that a subcommand is required. This is accomplished
+is not executable, meaning that a subcommand is required. This is accomplished
by not providing a 'Run' for the 'rootCmd'.
We have only defined one flag for a single command.
@@ -759,7 +753,7 @@ Cobra can generate documentation based on subcommands, flags, etc. Read more abo
## Generating shell completions
-Cobra can generate a shell-completion file for the following shells: Bash, Zsh, Fish, Powershell. If you add more information to your commands, these completions can be amazingly powerful and flexible. Read more about it in [Shell Completions](shell_completions.md).
+Cobra can generate a shell-completion file for the following shells: bash, zsh, fish, PowerShell. If you add more information to your commands, these completions can be amazingly powerful and flexible. Read more about it in [Shell Completions](shell_completions.md).
# License
diff --git a/vendor/github.com/spf13/cobra/bash_completions.go b/vendor/github.com/spf13/cobra/bash_completions.go
index 846636d75..710614793 100644
--- a/vendor/github.com/spf13/cobra/bash_completions.go
+++ b/vendor/github.com/spf13/cobra/bash_completions.go
@@ -19,9 +19,9 @@ const (
BashCompSubdirsInDir = "cobra_annotation_bash_completion_subdirs_in_dir"
)
-func writePreamble(buf *bytes.Buffer, name string) {
- buf.WriteString(fmt.Sprintf("# bash completion for %-36s -*- shell-script -*-\n", name))
- buf.WriteString(fmt.Sprintf(`
+func writePreamble(buf io.StringWriter, name string) {
+ WriteStringAndCheck(buf, fmt.Sprintf("# bash completion for %-36s -*- shell-script -*-\n", name))
+ WriteStringAndCheck(buf, fmt.Sprintf(`
__%[1]s_debug()
{
if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then
@@ -380,10 +380,10 @@ __%[1]s_handle_word()
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))
}
-func writePostscript(buf *bytes.Buffer, name string) {
+func writePostscript(buf io.StringWriter, name string) {
name = strings.Replace(name, ":", "__", -1)
- buf.WriteString(fmt.Sprintf("__start_%s()\n", name))
- buf.WriteString(fmt.Sprintf(`{
+ WriteStringAndCheck(buf, fmt.Sprintf("__start_%s()\n", name))
+ WriteStringAndCheck(buf, fmt.Sprintf(`{
local cur prev words cword
declare -A flaghash 2>/dev/null || :
declare -A aliashash 2>/dev/null || :
@@ -410,33 +410,33 @@ func writePostscript(buf *bytes.Buffer, name string) {
}
`, name))
- buf.WriteString(fmt.Sprintf(`if [[ $(type -t compopt) = "builtin" ]]; then
+ WriteStringAndCheck(buf, fmt.Sprintf(`if [[ $(type -t compopt) = "builtin" ]]; then
complete -o default -F __start_%s %s
else
complete -o default -o nospace -F __start_%s %s
fi
`, name, name, name, name))
- buf.WriteString("# ex: ts=4 sw=4 et filetype=sh\n")
+ WriteStringAndCheck(buf, "# ex: ts=4 sw=4 et filetype=sh\n")
}
-func writeCommands(buf *bytes.Buffer, cmd *Command) {
- buf.WriteString(" commands=()\n")
+func writeCommands(buf io.StringWriter, cmd *Command) {
+ WriteStringAndCheck(buf, " commands=()\n")
for _, c := range cmd.Commands() {
if !c.IsAvailableCommand() && c != cmd.helpCommand {
continue
}
- buf.WriteString(fmt.Sprintf(" commands+=(%q)\n", c.Name()))
+ WriteStringAndCheck(buf, fmt.Sprintf(" commands+=(%q)\n", c.Name()))
writeCmdAliases(buf, c)
}
- buf.WriteString("\n")
+ WriteStringAndCheck(buf, "\n")
}
-func writeFlagHandler(buf *bytes.Buffer, name string, annotations map[string][]string, cmd *Command) {
+func writeFlagHandler(buf io.StringWriter, name string, annotations map[string][]string, cmd *Command) {
for key, value := range annotations {
switch key {
case BashCompFilenameExt:
- buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name))
+ WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name))
var ext string
if len(value) > 0 {
@@ -444,17 +444,18 @@ func writeFlagHandler(buf *bytes.Buffer, name string, annotations map[string][]s
} else {
ext = "_filedir"
}
- buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", ext))
+ WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", ext))
case BashCompCustom:
- buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name))
+ WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name))
+
if len(value) > 0 {
handlers := strings.Join(value, "; ")
- buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", handlers))
+ WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", handlers))
} else {
- buf.WriteString(" flags_completion+=(:)\n")
+ WriteStringAndCheck(buf, " flags_completion+=(:)\n")
}
case BashCompSubdirsInDir:
- buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name))
+ WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name))
var ext string
if len(value) == 1 {
@@ -462,46 +463,48 @@ func writeFlagHandler(buf *bytes.Buffer, name string, annotations map[string][]s
} else {
ext = "_filedir -d"
}
- buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", ext))
+ WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", ext))
}
}
}
-func writeShortFlag(buf *bytes.Buffer, flag *pflag.Flag, cmd *Command) {
+const cbn = "\")\n"
+
+func writeShortFlag(buf io.StringWriter, flag *pflag.Flag, cmd *Command) {
name := flag.Shorthand
format := " "
if len(flag.NoOptDefVal) == 0 {
format += "two_word_"
}
- format += "flags+=(\"-%s\")\n"
- buf.WriteString(fmt.Sprintf(format, name))
+ format += "flags+=(\"-%s" + cbn
+ WriteStringAndCheck(buf, fmt.Sprintf(format, name))
writeFlagHandler(buf, "-"+name, flag.Annotations, cmd)
}
-func writeFlag(buf *bytes.Buffer, flag *pflag.Flag, cmd *Command) {
+func writeFlag(buf io.StringWriter, flag *pflag.Flag, cmd *Command) {
name := flag.Name
format := " flags+=(\"--%s"
if len(flag.NoOptDefVal) == 0 {
format += "="
}
- format += "\")\n"
- buf.WriteString(fmt.Sprintf(format, name))
+ format += cbn
+ WriteStringAndCheck(buf, fmt.Sprintf(format, name))
if len(flag.NoOptDefVal) == 0 {
- format = " two_word_flags+=(\"--%s\")\n"
- buf.WriteString(fmt.Sprintf(format, name))
+ format = " two_word_flags+=(\"--%s" + cbn
+ WriteStringAndCheck(buf, fmt.Sprintf(format, name))
}
writeFlagHandler(buf, "--"+name, flag.Annotations, cmd)
}
-func writeLocalNonPersistentFlag(buf *bytes.Buffer, flag *pflag.Flag) {
+func writeLocalNonPersistentFlag(buf io.StringWriter, flag *pflag.Flag) {
name := flag.Name
- format := " local_nonpersistent_flags+=(\"--%[1]s\")\n"
+ format := " local_nonpersistent_flags+=(\"--%[1]s" + cbn
if len(flag.NoOptDefVal) == 0 {
- format += " local_nonpersistent_flags+=(\"--%[1]s=\")\n"
+ format += " local_nonpersistent_flags+=(\"--%[1]s=" + cbn
}
- buf.WriteString(fmt.Sprintf(format, name))
+ WriteStringAndCheck(buf, fmt.Sprintf(format, name))
if len(flag.Shorthand) > 0 {
- buf.WriteString(fmt.Sprintf(" local_nonpersistent_flags+=(\"-%s\")\n", flag.Shorthand))
+ WriteStringAndCheck(buf, fmt.Sprintf(" local_nonpersistent_flags+=(\"-%s\")\n", flag.Shorthand))
}
}
@@ -519,9 +522,9 @@ func prepareCustomAnnotationsForFlags(cmd *Command) {
}
}
-func writeFlags(buf *bytes.Buffer, cmd *Command) {
+func writeFlags(buf io.StringWriter, cmd *Command) {
prepareCustomAnnotationsForFlags(cmd)
- buf.WriteString(` flags=()
+ WriteStringAndCheck(buf, ` flags=()
two_word_flags=()
local_nonpersistent_flags=()
flags_with_completion=()
@@ -553,11 +556,11 @@ func writeFlags(buf *bytes.Buffer, cmd *Command) {
}
})
- buf.WriteString("\n")
+ WriteStringAndCheck(buf, "\n")
}
-func writeRequiredFlag(buf *bytes.Buffer, cmd *Command) {
- buf.WriteString(" must_have_one_flag=()\n")
+func writeRequiredFlag(buf io.StringWriter, cmd *Command) {
+ WriteStringAndCheck(buf, " must_have_one_flag=()\n")
flags := cmd.NonInheritedFlags()
flags.VisitAll(func(flag *pflag.Flag) {
if nonCompletableFlag(flag) {
@@ -570,55 +573,55 @@ func writeRequiredFlag(buf *bytes.Buffer, cmd *Command) {
if flag.Value.Type() != "bool" {
format += "="
}
- format += "\")\n"
- buf.WriteString(fmt.Sprintf(format, flag.Name))
+ format += cbn
+ WriteStringAndCheck(buf, fmt.Sprintf(format, flag.Name))
if len(flag.Shorthand) > 0 {
- buf.WriteString(fmt.Sprintf(" must_have_one_flag+=(\"-%s\")\n", flag.Shorthand))
+ WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_flag+=(\"-%s"+cbn, flag.Shorthand))
}
}
}
})
}
-func writeRequiredNouns(buf *bytes.Buffer, cmd *Command) {
- buf.WriteString(" must_have_one_noun=()\n")
- sort.Sort(sort.StringSlice(cmd.ValidArgs))
+func writeRequiredNouns(buf io.StringWriter, cmd *Command) {
+ WriteStringAndCheck(buf, " must_have_one_noun=()\n")
+ sort.Strings(cmd.ValidArgs)
for _, value := range cmd.ValidArgs {
// Remove any description that may be included following a tab character.
// Descriptions are not supported by bash completion.
value = strings.Split(value, "\t")[0]
- buf.WriteString(fmt.Sprintf(" must_have_one_noun+=(%q)\n", value))
+ WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_noun+=(%q)\n", value))
}
if cmd.ValidArgsFunction != nil {
- buf.WriteString(" has_completion_function=1\n")
+ WriteStringAndCheck(buf, " has_completion_function=1\n")
}
}
-func writeCmdAliases(buf *bytes.Buffer, cmd *Command) {
+func writeCmdAliases(buf io.StringWriter, cmd *Command) {
if len(cmd.Aliases) == 0 {
return
}
- sort.Sort(sort.StringSlice(cmd.Aliases))
+ sort.Strings(cmd.Aliases)
- buf.WriteString(fmt.Sprint(` if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then`, "\n"))
+ WriteStringAndCheck(buf, fmt.Sprint(` if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then`, "\n"))
for _, value := range cmd.Aliases {
- buf.WriteString(fmt.Sprintf(" command_aliases+=(%q)\n", value))
- buf.WriteString(fmt.Sprintf(" aliashash[%q]=%q\n", value, cmd.Name()))
+ WriteStringAndCheck(buf, fmt.Sprintf(" command_aliases+=(%q)\n", value))
+ WriteStringAndCheck(buf, fmt.Sprintf(" aliashash[%q]=%q\n", value, cmd.Name()))
}
- buf.WriteString(` fi`)
- buf.WriteString("\n")
+ WriteStringAndCheck(buf, ` fi`)
+ WriteStringAndCheck(buf, "\n")
}
-func writeArgAliases(buf *bytes.Buffer, cmd *Command) {
- buf.WriteString(" noun_aliases=()\n")
- sort.Sort(sort.StringSlice(cmd.ArgAliases))
+func writeArgAliases(buf io.StringWriter, cmd *Command) {
+ WriteStringAndCheck(buf, " noun_aliases=()\n")
+ sort.Strings(cmd.ArgAliases)
for _, value := range cmd.ArgAliases {
- buf.WriteString(fmt.Sprintf(" noun_aliases+=(%q)\n", value))
+ WriteStringAndCheck(buf, fmt.Sprintf(" noun_aliases+=(%q)\n", value))
}
}
-func gen(buf *bytes.Buffer, cmd *Command) {
+func gen(buf io.StringWriter, cmd *Command) {
for _, c := range cmd.Commands() {
if !c.IsAvailableCommand() && c != cmd.helpCommand {
continue
@@ -630,22 +633,22 @@ func gen(buf *bytes.Buffer, cmd *Command) {
commandName = strings.Replace(commandName, ":", "__", -1)
if cmd.Root() == cmd {
- buf.WriteString(fmt.Sprintf("_%s_root_command()\n{\n", commandName))
+ WriteStringAndCheck(buf, fmt.Sprintf("_%s_root_command()\n{\n", commandName))
} else {
- buf.WriteString(fmt.Sprintf("_%s()\n{\n", commandName))
+ WriteStringAndCheck(buf, fmt.Sprintf("_%s()\n{\n", commandName))
}
- buf.WriteString(fmt.Sprintf(" last_command=%q\n", commandName))
- buf.WriteString("\n")
- buf.WriteString(" command_aliases=()\n")
- buf.WriteString("\n")
+ WriteStringAndCheck(buf, fmt.Sprintf(" last_command=%q\n", commandName))
+ WriteStringAndCheck(buf, "\n")
+ WriteStringAndCheck(buf, " command_aliases=()\n")
+ WriteStringAndCheck(buf, "\n")
writeCommands(buf, cmd)
writeFlags(buf, cmd)
writeRequiredFlag(buf, cmd)
writeRequiredNouns(buf, cmd)
writeArgAliases(buf, cmd)
- buf.WriteString("}\n\n")
+ WriteStringAndCheck(buf, "}\n\n")
}
// GenBashCompletion generates bash completion file and writes to the passed writer.
diff --git a/vendor/github.com/spf13/cobra/bash_completions.md b/vendor/github.com/spf13/cobra/bash_completions.md
index a82d5bb8b..130f99b92 100644
--- a/vendor/github.com/spf13/cobra/bash_completions.md
+++ b/vendor/github.com/spf13/cobra/bash_completions.md
@@ -4,7 +4,7 @@ Please refer to [Shell Completions](shell_completions.md) for details.
## Bash legacy dynamic completions
-For backwards-compatibility, Cobra still supports its legacy dynamic completion solution (described below). Unlike the `ValidArgsFunction` solution, the legacy solution will only work for Bash shell-completion and not for other shells. This legacy solution can be used along-side `ValidArgsFunction` and `RegisterFlagCompletionFunc()`, as long as both solutions are not used for the same command. This provides a path to gradually migrate from the legacy solution to the new solution.
+For backward compatibility, Cobra still supports its legacy dynamic completion solution (described below). Unlike the `ValidArgsFunction` solution, the legacy solution will only work for Bash shell-completion and not for other shells. This legacy solution can be used along-side `ValidArgsFunction` and `RegisterFlagCompletionFunc()`, as long as both solutions are not used for the same command. This provides a path to gradually migrate from the legacy solution to the new solution.
The legacy solution allows you to inject bash functions into the bash completion script. Those bash functions are responsible for providing the completion choices for your own completions.
diff --git a/vendor/github.com/spf13/cobra/cobra.go b/vendor/github.com/spf13/cobra/cobra.go
index d01becc8f..d6cbfd719 100644
--- a/vendor/github.com/spf13/cobra/cobra.go
+++ b/vendor/github.com/spf13/cobra/cobra.go
@@ -19,6 +19,7 @@ package cobra
import (
"fmt"
"io"
+ "os"
"reflect"
"strconv"
"strings"
@@ -205,3 +206,17 @@ func stringInSlice(a string, list []string) bool {
}
return false
}
+
+// CheckErr prints the msg with the prefix 'Error:' and exits with error code 1. If the msg is nil, it does nothing.
+func CheckErr(msg interface{}) {
+ if msg != nil {
+ fmt.Fprintln(os.Stderr, "Error:", msg)
+ os.Exit(1)
+ }
+}
+
+// WriteStringAndCheck writes a string into a buffer, and checks if the error is not nil.
+func WriteStringAndCheck(b io.StringWriter, s string) {
+ _, err := b.WriteString(s)
+ CheckErr(err)
+}
diff --git a/vendor/github.com/spf13/cobra/command.go b/vendor/github.com/spf13/cobra/command.go
index 77b399e02..d6732ad11 100644
--- a/vendor/github.com/spf13/cobra/command.go
+++ b/vendor/github.com/spf13/cobra/command.go
@@ -84,9 +84,6 @@ type Command struct {
// Deprecated defines, if this command is deprecated and should print this string when used.
Deprecated string
- // Hidden defines, if this command is hidden and should NOT show up in the list of available commands.
- Hidden bool
-
// Annotations are key/value pairs that can be used by applications to identify or
// group commands.
Annotations map[string]string
@@ -126,55 +123,6 @@ type Command struct {
// PersistentPostRunE: PersistentPostRun but returns an error.
PersistentPostRunE func(cmd *Command, args []string) error
- // SilenceErrors is an option to quiet errors down stream.
- SilenceErrors bool
-
- // SilenceUsage is an option to silence usage when an error occurs.
- SilenceUsage bool
-
- // DisableFlagParsing disables the flag parsing.
- // If this is true all flags will be passed to the command as arguments.
- DisableFlagParsing bool
-
- // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")
- // will be printed by generating docs for this command.
- DisableAutoGenTag bool
-
- // DisableFlagsInUseLine will disable the addition of [flags] to the usage
- // line of a command when printing help or generating docs
- DisableFlagsInUseLine bool
-
- // DisableSuggestions disables the suggestions based on Levenshtein distance
- // that go along with 'unknown command' messages.
- DisableSuggestions bool
- // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.
- // Must be > 0.
- SuggestionsMinimumDistance int
-
- // TraverseChildren parses flags on all parents before executing child command.
- TraverseChildren bool
-
- // FParseErrWhitelist flag parse errors to be ignored
- FParseErrWhitelist FParseErrWhitelist
-
- ctx context.Context
-
- // commands is the list of commands supported by this program.
- commands []*Command
- // parent is a parent command for this command.
- parent *Command
- // Max lengths of commands' string lengths for use in padding.
- commandsMaxUseLen int
- commandsMaxCommandPathLen int
- commandsMaxNameLen int
- // commandsAreSorted defines, if command slice are sorted or not.
- commandsAreSorted bool
- // commandCalledAs is the name or alias value used to call this command.
- commandCalledAs struct {
- name string
- called bool
- }
-
// args is actual args parsed from flags.
args []string
// flagErrorBuf contains all error messages from pflag.
@@ -216,6 +164,60 @@ type Command struct {
outWriter io.Writer
// errWriter is a writer defined by the user that replaces stderr
errWriter io.Writer
+
+ //FParseErrWhitelist flag parse errors to be ignored
+ FParseErrWhitelist FParseErrWhitelist
+
+ // commandsAreSorted defines, if command slice are sorted or not.
+ commandsAreSorted bool
+ // commandCalledAs is the name or alias value used to call this command.
+ commandCalledAs struct {
+ name string
+ called bool
+ }
+
+ ctx context.Context
+
+ // commands is the list of commands supported by this program.
+ commands []*Command
+ // parent is a parent command for this command.
+ parent *Command
+ // Max lengths of commands' string lengths for use in padding.
+ commandsMaxUseLen int
+ commandsMaxCommandPathLen int
+ commandsMaxNameLen int
+
+ // TraverseChildren parses flags on all parents before executing child command.
+ TraverseChildren bool
+
+ // Hidden defines, if this command is hidden and should NOT show up in the list of available commands.
+ Hidden bool
+
+ // SilenceErrors is an option to quiet errors down stream.
+ SilenceErrors bool
+
+ // SilenceUsage is an option to silence usage when an error occurs.
+ SilenceUsage bool
+
+ // DisableFlagParsing disables the flag parsing.
+ // If this is true all flags will be passed to the command as arguments.
+ DisableFlagParsing bool
+
+ // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")
+ // will be printed by generating docs for this command.
+ DisableAutoGenTag bool
+
+ // DisableFlagsInUseLine will disable the addition of [flags] to the usage
+ // line of a command when printing help or generating docs
+ DisableFlagsInUseLine bool
+
+ // DisableSuggestions disables the suggestions based on Levenshtein distance
+ // that go along with 'unknown command' messages.
+ DisableSuggestions bool
+
+ // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.
+ // Must be > 0.
+ SuggestionsMinimumDistance int
}
// Context returns underlying command context. If command wasn't
@@ -418,7 +420,7 @@ func (c *Command) UsageString() string {
c.outWriter = bb
c.errWriter = bb
- c.Usage()
+ CheckErr(c.Usage())
// Setting things back to normal
c.outWriter = tmpOutput
@@ -964,13 +966,13 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
return cmd, nil
}
- // If root command has SilentErrors flagged,
+ // If root command has SilenceErrors flagged,
// all subcommands should respect it
if !cmd.SilenceErrors && !c.SilenceErrors {
c.PrintErrln("Error:", err.Error())
}
- // If root command has SilentUsage flagged,
+ // If root command has SilenceUsage flagged,
// all subcommands should respect it
if !cmd.SilenceUsage && !c.SilenceUsage {
c.Println(cmd.UsageString())
@@ -1087,10 +1089,10 @@ Simply type ` + c.Name() + ` help [path to command] for full details.`,
cmd, _, e := c.Root().Find(args)
if cmd == nil || e != nil {
c.Printf("Unknown help topic %#q\n", args)
- c.Root().Usage()
+ CheckErr(c.Root().Usage())
} else {
cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown
- cmd.Help()
+ CheckErr(cmd.Help())
}
},
}
diff --git a/vendor/github.com/spf13/cobra/custom_completions.go b/vendor/github.com/spf13/cobra/custom_completions.go
index f9e88e081..fa060c147 100644
--- a/vendor/github.com/spf13/cobra/custom_completions.go
+++ b/vendor/github.com/spf13/cobra/custom_completions.go
@@ -527,13 +527,13 @@ func CompDebug(msg string, printToStdErr bool) {
os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err == nil {
defer f.Close()
- f.WriteString(msg)
+ WriteStringAndCheck(f, msg)
}
}
if printToStdErr {
// Must print to stderr for this not to be read by the completion script.
- fmt.Fprintf(os.Stderr, msg)
+ fmt.Fprint(os.Stderr, msg)
}
}
diff --git a/vendor/github.com/spf13/cobra/fish_completions.go b/vendor/github.com/spf13/cobra/fish_completions.go
index eaae9bca8..3e112347d 100644
--- a/vendor/github.com/spf13/cobra/fish_completions.go
+++ b/vendor/github.com/spf13/cobra/fish_completions.go
@@ -8,7 +8,7 @@ import (
"strings"
)
-func genFishComp(buf *bytes.Buffer, name string, includeDesc bool) {
+func genFishComp(buf io.StringWriter, name string, includeDesc bool) {
// Variables should not contain a '-' or ':' character
nameForVar := name
nameForVar = strings.Replace(nameForVar, "-", "_", -1)
@@ -18,8 +18,8 @@ func genFishComp(buf *bytes.Buffer, name string, includeDesc bool) {
if !includeDesc {
compCmd = ShellCompNoDescRequestCmd
}
- buf.WriteString(fmt.Sprintf("# fish completion for %-36s -*- shell-script -*-\n", name))
- buf.WriteString(fmt.Sprintf(`
+ WriteStringAndCheck(buf, fmt.Sprintf("# fish completion for %-36s -*- shell-script -*-\n", name))
+ WriteStringAndCheck(buf, fmt.Sprintf(`
function __%[1]s_debug
set file "$BASH_COMP_DEBUG_FILE"
if test -n "$file"
diff --git a/vendor/github.com/spf13/cobra/go.mod b/vendor/github.com/spf13/cobra/go.mod
index 57e3244d5..eb7d47fa5 100644
--- a/vendor/github.com/spf13/cobra/go.mod
+++ b/vendor/github.com/spf13/cobra/go.mod
@@ -1,6 +1,6 @@
module github.com/spf13/cobra
-go 1.12
+go 1.14
require (
github.com/cpuguy83/go-md2man/v2 v2.0.0
@@ -8,5 +8,5 @@ require (
github.com/mitchellh/go-homedir v1.1.0
github.com/spf13/pflag v1.0.5
github.com/spf13/viper v1.7.0
- gopkg.in/yaml.v2 v2.2.8
+ gopkg.in/yaml.v2 v2.4.0
)
diff --git a/vendor/github.com/spf13/cobra/go.sum b/vendor/github.com/spf13/cobra/go.sum
index 0aae73863..9328ee3ee 100644
--- a/vendor/github.com/spf13/cobra/go.sum
+++ b/vendor/github.com/spf13/cobra/go.sum
@@ -304,8 +304,8 @@ gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo=
gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
-gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
-gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
+gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
+gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
diff --git a/vendor/github.com/spf13/cobra/powershell_completions.go b/vendor/github.com/spf13/cobra/powershell_completions.go
index 756c61b9d..c55be71cd 100644
--- a/vendor/github.com/spf13/cobra/powershell_completions.go
+++ b/vendor/github.com/spf13/cobra/powershell_completions.go
@@ -1,6 +1,3 @@
-// PowerShell completions are based on the amazing work from clap:
-// https://github.com/clap-rs/clap/blob/3294d18efe5f264d12c9035f404c7d189d4824e1/src/completions/powershell.rs
-//
// The generated scripts require PowerShell v5.0+ (which comes Windows 10, but
// can be downloaded separately for windows 7 or 8.1).
@@ -11,90 +8,278 @@ import (
"fmt"
"io"
"os"
- "strings"
-
- "github.com/spf13/pflag"
)
-var powerShellCompletionTemplate = `using namespace System.Management.Automation
-using namespace System.Management.Automation.Language
-Register-ArgumentCompleter -Native -CommandName '%s' -ScriptBlock {
- param($wordToComplete, $commandAst, $cursorPosition)
- $commandElements = $commandAst.CommandElements
- $command = @(
- '%s'
- for ($i = 1; $i -lt $commandElements.Count; $i++) {
- $element = $commandElements[$i]
- if ($element -isnot [StringConstantExpressionAst] -or
- $element.StringConstantType -ne [StringConstantType]::BareWord -or
- $element.Value.StartsWith('-')) {
- break
- }
- $element.Value
- }
- ) -join ';'
- $completions = @(switch ($command) {%s
- })
- $completions.Where{ $_.CompletionText -like "$wordToComplete*" } |
- Sort-Object -Property ListItemText
-}`
-
-func generatePowerShellSubcommandCases(out io.Writer, cmd *Command, previousCommandName string) {
- var cmdName string
- if previousCommandName == "" {
- cmdName = cmd.Name()
- } else {
- cmdName = fmt.Sprintf("%s;%s", previousCommandName, cmd.Name())
- }
-
- fmt.Fprintf(out, "\n '%s' {", cmdName)
-
- cmd.Flags().VisitAll(func(flag *pflag.Flag) {
- if nonCompletableFlag(flag) {
- return
- }
- usage := escapeStringForPowerShell(flag.Usage)
- if len(flag.Shorthand) > 0 {
- fmt.Fprintf(out, "\n [CompletionResult]::new('-%s', '%s', [CompletionResultType]::ParameterName, '%s')", flag.Shorthand, flag.Shorthand, usage)
- }
- fmt.Fprintf(out, "\n [CompletionResult]::new('--%s', '%s', [CompletionResultType]::ParameterName, '%s')", flag.Name, flag.Name, usage)
- })
-
- for _, subCmd := range cmd.Commands() {
- usage := escapeStringForPowerShell(subCmd.Short)
- fmt.Fprintf(out, "\n [CompletionResult]::new('%s', '%s', [CompletionResultType]::ParameterValue, '%s')", subCmd.Name(), subCmd.Name(), usage)
+func genPowerShellComp(buf io.StringWriter, name string, includeDesc bool) {
+ compCmd := ShellCompRequestCmd
+ if !includeDesc {
+ compCmd = ShellCompNoDescRequestCmd
}
+ WriteStringAndCheck(buf, fmt.Sprintf(`# powershell completion for %-36[1]s -*- shell-script -*-
- fmt.Fprint(out, "\n break\n }")
-
- for _, subCmd := range cmd.Commands() {
- generatePowerShellSubcommandCases(out, subCmd, cmdName)
- }
+function __%[1]s_debug {
+ if ($env:BASH_COMP_DEBUG_FILE) {
+ "$args" | Out-File -Append -FilePath "$env:BASH_COMP_DEBUG_FILE"
+ }
}
-func escapeStringForPowerShell(s string) string {
- return strings.Replace(s, "'", "''", -1)
+filter __%[1]s_escapeStringWithSpecialChars {
+`+" $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|\"|`|\\||<|>|&','`$&'"+`
}
-// GenPowerShellCompletion generates PowerShell completion file and writes to the passed writer.
-func (c *Command) GenPowerShellCompletion(w io.Writer) error {
- buf := new(bytes.Buffer)
+Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock {
+ param(
+ $WordToComplete,
+ $CommandAst,
+ $CursorPosition
+ )
+
+ # Get the current command line and convert into a string
+ $Command = $CommandAst.CommandElements
+ $Command = "$Command"
+
+ __%[1]s_debug ""
+ __%[1]s_debug "========= starting completion logic =========="
+ __%[1]s_debug "WordToComplete: $WordToComplete Command: $Command CursorPosition: $CursorPosition"
+
+ # The user could have moved the cursor backwards on the command-line.
+ # We need to trigger completion from the $CursorPosition location, so we need
+ # to truncate the command-line ($Command) up to the $CursorPosition location.
+ # Make sure the $Command is longer then the $CursorPosition before we truncate.
+ # This happens because the $Command does not include the last space.
+ if ($Command.Length -gt $CursorPosition) {
+ $Command=$Command.Substring(0,$CursorPosition)
+ }
+ __%[1]s_debug "Truncated command: $Command"
+
+ $ShellCompDirectiveError=%[3]d
+ $ShellCompDirectiveNoSpace=%[4]d
+ $ShellCompDirectiveNoFileComp=%[5]d
+ $ShellCompDirectiveFilterFileExt=%[6]d
+ $ShellCompDirectiveFilterDirs=%[7]d
+
+ # Prepare the command to request completions for the program.
+ # Split the command at the first space to separate the program and arguments.
+ $Program,$Arguments = $Command.Split(" ",2)
+ $RequestComp="$Program %[2]s $Arguments"
+ __%[1]s_debug "RequestComp: $RequestComp"
+
+ # we cannot use $WordToComplete because it
+ # has the wrong values if the cursor was moved
+ # so use the last argument
+ if ($WordToComplete -ne "" ) {
+ $WordToComplete = $Arguments.Split(" ")[-1]
+ }
+ __%[1]s_debug "New WordToComplete: $WordToComplete"
+
+
+ # Check for flag with equal sign
+ $IsEqualFlag = ($WordToComplete -Like "--*=*" )
+ if ( $IsEqualFlag ) {
+ __%[1]s_debug "Completing equal sign flag"
+ # Remove the flag part
+ $Flag,$WordToComplete = $WordToComplete.Split("=",2)
+ }
+
+ if ( $WordToComplete -eq "" -And ( -Not $IsEqualFlag )) {
+ # If the last parameter is complete (there is a space following it)
+ # We add an extra empty parameter so we can indicate this to the go method.
+ __%[1]s_debug "Adding extra empty parameter"
+`+" # We need to use `\"`\" to pass an empty argument a \"\" or '' does not work!!!"+`
+`+" $RequestComp=\"$RequestComp\" + ' `\"`\"' "+`
+ }
+
+ __%[1]s_debug "Calling $RequestComp"
+ #call the command store the output in $out and redirect stderr and stdout to null
+ # $Out is an array contains each line per element
+ Invoke-Expression -OutVariable out "$RequestComp" 2>&1 | Out-Null
+
+
+ # get directive from last line
+ [int]$Directive = $Out[-1].TrimStart(':')
+ if ($Directive -eq "") {
+ # There is no directive specified
+ $Directive = 0
+ }
+ __%[1]s_debug "The completion directive is: $Directive"
+
+ # remove directive (last element) from out
+ $Out = $Out | Where-Object { $_ -ne $Out[-1] }
+ __%[1]s_debug "The completions are: $Out"
+
+ if (($Directive -band $ShellCompDirectiveError) -ne 0 ) {
+ # Error code. No completion.
+ __%[1]s_debug "Received error from custom completion go code"
+ return
+ }
+
+ $Longest = 0
+ $Values = $Out | ForEach-Object {
+ #Split the output in name and description
+`+" $Name, $Description = $_.Split(\"`t\",2)"+`
+ __%[1]s_debug "Name: $Name Description: $Description"
+
+ # Look for the longest completion so that we can format things nicely
+ if ($Longest -lt $Name.Length) {
+ $Longest = $Name.Length
+ }
+
+ # Set the description to a one space string if there is none set.
+ # This is needed because the CompletionResult does not accept an empty string as argument
+ if (-Not $Description) {
+ $Description = " "
+ }
+ @{Name="$Name";Description="$Description"}
+ }
+
+
+ $Space = " "
+ if (($Directive -band $ShellCompDirectiveNoSpace) -ne 0 ) {
+ # remove the space here
+ __%[1]s_debug "ShellCompDirectiveNoSpace is called"
+ $Space = ""
+ }
+
+ if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) {
+ __%[1]s_debug "ShellCompDirectiveNoFileComp is called"
+
+ if ($Values.Length -eq 0) {
+ # Just print an empty string here so the
+ # shell does not start to complete paths.
+ # We cannot use CompletionResult here because
+ # it does not accept an empty string as argument.
+ ""
+ return
+ }
+ }
+
+ if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or
+ (($Directive -band $ShellCompDirectiveFilterDirs) -ne 0 )) {
+ __%[1]s_debug "ShellCompDirectiveFilterFileExt ShellCompDirectiveFilterDirs are not supported"
+
+ # return here to prevent the completion of the extensions
+ return
+ }
- var subCommandCases bytes.Buffer
- generatePowerShellSubcommandCases(&subCommandCases, c, "")
- fmt.Fprintf(buf, powerShellCompletionTemplate, c.Name(), c.Name(), subCommandCases.String())
+ $Values = $Values | Where-Object {
+ # filter the result
+ $_.Name -like "$WordToComplete*"
+ # Join the flag back if we have a equal sign flag
+ if ( $IsEqualFlag ) {
+ __%[1]s_debug "Join the equal sign flag back to the completion value"
+ $_.Name = $Flag + "=" + $_.Name
+ }
+ }
+
+ # Get the current mode
+ $Mode = (Get-PSReadLineKeyHandler | Where-Object {$_.Key -eq "Tab" }).Function
+ __%[1]s_debug "Mode: $Mode"
+
+ $Values | ForEach-Object {
+
+ # store temporay because switch will overwrite $_
+ $comp = $_
+
+ # PowerShell supports three different completion modes
+ # - TabCompleteNext (default windows style - on each key press the next option is displayed)
+ # - Complete (works like bash)
+ # - MenuComplete (works like zsh)
+ # You set the mode with Set-PSReadLineKeyHandler -Key Tab -Function <mode>
+
+ # CompletionResult Arguments:
+ # 1) CompletionText text to be used as the auto completion result
+ # 2) ListItemText text to be displayed in the suggestion list
+ # 3) ResultType type of completion result
+ # 4) ToolTip text for the tooltip with details about the object
+
+ switch ($Mode) {
+
+ # bash like
+ "Complete" {
+
+ if ($Values.Length -eq 1) {
+ __%[1]s_debug "Only one completion left"
+
+ # insert space after value
+ [System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
+
+ } else {
+ # Add the proper number of spaces to align the descriptions
+ while($comp.Name.Length -lt $Longest) {
+ $comp.Name = $comp.Name + " "
+ }
+
+ # Check for empty description and only add parentheses if needed
+ if ($($comp.Description) -eq " " ) {
+ $Description = ""
+ } else {
+ $Description = " ($($comp.Description))"
+ }
+
+ [System.Management.Automation.CompletionResult]::new("$($comp.Name)$Description", "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)")
+ }
+ }
+
+ # zsh like
+ "MenuComplete" {
+ # insert space after value
+ # MenuComplete will automatically show the ToolTip of
+ # the highlighted value at the bottom of the suggestions.
+ [System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
+ }
+
+ # TabCompleteNext and in case we get something unknown
+ Default {
+ # Like MenuComplete but we don't want to add a space here because
+ # the user need to press space anyway to get the completion.
+ # Description will not be shown because thats not possible with TabCompleteNext
+ [System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars), "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
+ }
+ }
+
+ }
+}
+`, name, compCmd,
+ ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
+ ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))
+}
+
+func (c *Command) genPowerShellCompletion(w io.Writer, includeDesc bool) error {
+ buf := new(bytes.Buffer)
+ genPowerShellComp(buf, c.Name(), includeDesc)
_, err := buf.WriteTo(w)
return err
}
-// GenPowerShellCompletionFile generates PowerShell completion file.
-func (c *Command) GenPowerShellCompletionFile(filename string) error {
+func (c *Command) genPowerShellCompletionFile(filename string, includeDesc bool) error {
outFile, err := os.Create(filename)
if err != nil {
return err
}
defer outFile.Close()
- return c.GenPowerShellCompletion(outFile)
+ return c.genPowerShellCompletion(outFile, includeDesc)
+}
+
+// GenPowerShellCompletionFile generates powershell completion file without descriptions.
+func (c *Command) GenPowerShellCompletionFile(filename string) error {
+ return c.genPowerShellCompletionFile(filename, false)
+}
+
+// GenPowerShellCompletion generates powershell completion file without descriptions
+// and writes it to the passed writer.
+func (c *Command) GenPowerShellCompletion(w io.Writer) error {
+ return c.genPowerShellCompletion(w, false)
+}
+
+// GenPowerShellCompletionFileWithDesc generates powershell completion file with descriptions.
+func (c *Command) GenPowerShellCompletionFileWithDesc(filename string) error {
+ return c.genPowerShellCompletionFile(filename, true)
+}
+
+// GenPowerShellCompletionWithDesc generates powershell completion file with descriptions
+// and writes it to the passed writer.
+func (c *Command) GenPowerShellCompletionWithDesc(w io.Writer) error {
+ return c.genPowerShellCompletion(w, true)
}
diff --git a/vendor/github.com/spf13/cobra/powershell_completions.md b/vendor/github.com/spf13/cobra/powershell_completions.md
index 55f154a68..c449f1e5c 100644
--- a/vendor/github.com/spf13/cobra/powershell_completions.md
+++ b/vendor/github.com/spf13/cobra/powershell_completions.md
@@ -1,16 +1,3 @@
# Generating PowerShell Completions For Your Own cobra.Command
-Cobra can generate PowerShell completion scripts. Users need PowerShell version 5.0 or above, which comes with Windows 10 and can be downloaded separately for Windows 7 or 8.1. They can then write the completions to a file and source this file from their PowerShell profile, which is referenced by the `$Profile` environment variable. See `Get-Help about_Profiles` for more info about PowerShell profiles.
-
-*Note*: PowerShell completions have not (yet?) been aligned to Cobra's generic shell completion support. This implies the PowerShell completions are not as rich as for other shells (see [What's not yet supported](#whats-not-yet-supported)), and may behave slightly differently. They are still very useful for PowerShell users.
-
-# What's supported
-
-- Completion for subcommands using their `.Short` description
-- Completion for non-hidden flags using their `.Name` and `.Shorthand`
-
-# What's not yet supported
-
-- Command aliases
-- Required, filename or custom flags (they will work like normal flags)
-- Custom completion scripts
+Please refer to [Shell Completions](shell_completions.md#powershell-completions) for details.
diff --git a/vendor/github.com/spf13/cobra/projects_using_cobra.md b/vendor/github.com/spf13/cobra/projects_using_cobra.md
index 31c272036..d98a71e36 100644
--- a/vendor/github.com/spf13/cobra/projects_using_cobra.md
+++ b/vendor/github.com/spf13/cobra/projects_using_cobra.md
@@ -25,6 +25,8 @@
- [Moby (former Docker)](https://github.com/moby/moby)
- [Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack)
- [OpenShift](https://www.openshift.com/)
+- [Ory Hydra](https://github.com/ory/hydra)
+- [Ory Kratos](https://github.com/ory/kratos)
- [Pouch](https://github.com/alibaba/pouch)
- [ProjectAtomic (enterprise)](http://www.projectatomic.io/)
- [Prototool](https://github.com/uber/prototool)
@@ -32,4 +34,5 @@
- [Rclone](https://rclone.org/)
- [Skaffold](https://skaffold.dev/)
- [Tendermint](https://github.com/tendermint/tendermint)
+- [Twitch CLI](https://github.com/twitchdev/twitch-cli)
- [Werf](https://werf.io/)
diff --git a/vendor/github.com/spf13/cobra/shell_completions.md b/vendor/github.com/spf13/cobra/shell_completions.md
index d8416ab1d..cd533ac3d 100644
--- a/vendor/github.com/spf13/cobra/shell_completions.md
+++ b/vendor/github.com/spf13/cobra/shell_completions.md
@@ -4,10 +4,10 @@ Cobra can generate shell completions for multiple shells.
The currently supported shells are:
- Bash
- Zsh
-- Fish
+- fish
- PowerShell
-If you are using the generator you can create a completion command by running
+If you are using the generator, you can create a completion command by running
```bash
cobra add completion
@@ -17,38 +17,46 @@ and then modifying the generated `cmd/completion.go` file to look something like
```go
var completionCmd = &cobra.Command{
- Use: "completion [bash|zsh|fish|powershell]",
- Short: "Generate completion script",
+ Use: "completion [bash|zsh|fish|powershell]",
+ Short: "Generate completion script",
Long: `To load completions:
Bash:
-$ source <(yourprogram completion bash)
+ $ source <(yourprogram completion bash)
-# To load completions for each session, execute once:
-Linux:
+ # To load completions for each session, execute once:
+ # Linux:
$ yourprogram completion bash > /etc/bash_completion.d/yourprogram
-MacOS:
+ # macOS:
$ yourprogram completion bash > /usr/local/etc/bash_completion.d/yourprogram
Zsh:
-# If shell completion is not already enabled in your environment you will need
-# to enable it. You can execute the following once:
+ # If shell completion is not already enabled in your environment,
+ # you will need to enable it. You can execute the following once:
-$ echo "autoload -U compinit; compinit" >> ~/.zshrc
+ $ echo "autoload -U compinit; compinit" >> ~/.zshrc
-# To load completions for each session, execute once:
-$ yourprogram completion zsh > "${fpath[1]}/_yourprogram"
+ # To load completions for each session, execute once:
+ $ yourprogram completion zsh > "${fpath[1]}/_yourprogram"
-# You will need to start a new shell for this setup to take effect.
+ # You will need to start a new shell for this setup to take effect.
-Fish:
+fish:
-$ yourprogram completion fish | source
+ $ yourprogram completion fish | source
-# To load completions for each session, execute once:
-$ yourprogram completion fish > ~/.config/fish/completions/yourprogram.fish
+ # To load completions for each session, execute once:
+ $ yourprogram completion fish > ~/.config/fish/completions/yourprogram.fish
+
+PowerShell:
+
+ PS> yourprogram completion powershell | Out-String | Invoke-Expression
+
+ # To load completions for every new session, run:
+ PS> yourprogram completion powershell > yourprogram.ps1
+ # and source this file from your PowerShell profile.
`,
DisableFlagsInUseLine: true,
ValidArgs: []string{"bash", "zsh", "fish", "powershell"},
@@ -68,7 +76,7 @@ $ yourprogram completion fish > ~/.config/fish/completions/yourprogram.fish
}
```
-**Note:** The cobra generator may include messages printed to stdout for example if the config file is loaded, this will break the auto complete script so must be removed.
+**Note:** The cobra generator may include messages printed to stdout, for example, if the config file is loaded; this will break the auto-completion script so must be removed.
# Customizing completions
@@ -91,8 +99,7 @@ cmd := &cobra.Command{
Long: get_long,
Example: get_example,
Run: func(cmd *cobra.Command, args []string) {
- err := RunGet(f, out, cmd, args)
- util.CheckErr(err)
+ cobra.CheckErr(RunGet(f, out, cmd, args))
},
ValidArgs: validArgs,
}
@@ -124,7 +131,7 @@ the completion algorithm if entered manually, e.g. in:
```bash
$ kubectl get rc [tab][tab]
-backend frontend database
+backend frontend database
```
Note that without declaring `rc` as an alias, the completion algorithm would not know to show the list of
@@ -246,7 +253,7 @@ and you'll get something like
```bash
$ kubectl exec [tab][tab]
--c --container= -p --pod=
+-c --container= -p --pod=
```
### Specify dynamic flag completion
@@ -316,7 +323,7 @@ cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string,
```
### Descriptions for completions
-Both `zsh` and `fish` allow for descriptions to annotate completion choices. For commands and flags, Cobra will provide the descriptions automatically, based on usage information. For example, using zsh:
+`zsh`, `fish` and `powershell` allow for descriptions to annotate completion choices. For commands and flags, Cobra will provide the descriptions automatically, based on usage information. For example, using zsh:
```
$ helm s[tab]
search -- search for a keyword in charts
@@ -361,12 +368,12 @@ completion firstcommand secondcommand
```
### Bash legacy dynamic completions
-For backwards-compatibility, Cobra still supports its bash legacy dynamic completion solution.
+For backward compatibility, Cobra still supports its bash legacy dynamic completion solution.
Please refer to [Bash Completions](bash_completions.md) for details.
## Zsh completions
-Cobra supports native Zsh completion generated from the root `cobra.Command`.
+Cobra supports native zsh completion generated from the root `cobra.Command`.
The generated completion script should be put somewhere in your `$fpath` and be named
`_<yourProgram>`. You will need to start a new shell for the completions to become available.
@@ -385,23 +392,23 @@ status -- displays the status of the named release
$ helm s[tab]
search show status
```
-*Note*: Because of backwards-compatibility requirements, we were forced to have a different API to disable completion descriptions between `Zsh` and `Fish`.
+*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`.
### Limitations
* Custom completions implemented in Bash scripting (legacy) are not supported and will be ignored for `zsh` (including the use of the `BashCompCustom` flag annotation).
- * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`).
+ * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`).
* The function `MarkFlagCustom()` is not supported and will be ignored for `zsh`.
* You should instead use `RegisterFlagCompletionFunc()`.
### Zsh completions standardization
-Cobra 1.1 standardized its zsh completion support to align it with its other shell completions. Although the API was kept backwards-compatible, some small changes in behavior were introduced.
+Cobra 1.1 standardized its zsh completion support to align it with its other shell completions. Although the API was kept backward-compatible, some small changes in behavior were introduced.
Please refer to [Zsh Completions](zsh_completions.md) for details.
-## Fish completions
+## fish completions
-Cobra supports native Fish completions generated from the root `cobra.Command`. You can use the `command.GenFishCompletion()` or `command.GenFishCompletionFile()` functions. You must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users.
+Cobra supports native fish completions generated from the root `cobra.Command`. You can use the `command.GenFishCompletion()` or `command.GenFishCompletionFile()` functions. You must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users.
```
# With descriptions
$ helm s[tab]
@@ -411,12 +418,12 @@ search (search for a keyword in charts) show (show information of a chart) s
$ helm s[tab]
search show status
```
-*Note*: Because of backwards-compatibility requirements, we were forced to have a different API to disable completion descriptions between `Zsh` and `Fish`.
+*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`.
### Limitations
-* Custom completions implemented in Bash scripting (legacy) are not supported and will be ignored for `fish` (including the use of the `BashCompCustom` flag annotation).
- * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`).
+* Custom completions implemented in bash scripting (legacy) are not supported and will be ignored for `fish` (including the use of the `BashCompCustom` flag annotation).
+ * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`).
* The function `MarkFlagCustom()` is not supported and will be ignored for `fish`.
* You should instead use `RegisterFlagCompletionFunc()`.
* The following flag completion annotations are not supported and will be ignored for `fish`:
@@ -431,4 +438,46 @@ search show status
## PowerShell completions
-Please refer to [PowerShell Completions](powershell_completions.md) for details.
+Cobra supports native PowerShell completions generated from the root `cobra.Command`. You can use the `command.GenPowerShellCompletion()` or `command.GenPowerShellCompletionFile()` functions. To include descriptions use `command.GenPowerShellCompletionWithDesc()` and `command.GenPowerShellCompletionFileWithDesc()`. Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users.
+
+The script is designed to support all three PowerShell completion modes:
+
+* TabCompleteNext (default windows style - on each key press the next option is displayed)
+* Complete (works like bash)
+* MenuComplete (works like zsh)
+
+You set the mode with `Set-PSReadLineKeyHandler -Key Tab -Function <mode>`. Descriptions are only displayed when using the `Complete` or `MenuComplete` mode.
+
+Users need PowerShell version 5.0 or above, which comes with Windows 10 and can be downloaded separately for Windows 7 or 8.1. They can then write the completions to a file and source this file from their PowerShell profile, which is referenced by the `$Profile` environment variable. See `Get-Help about_Profiles` for more info about PowerShell profiles.
+
+```
+# With descriptions and Mode 'Complete'
+$ helm s[tab]
+search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release)
+
+# With descriptions and Mode 'MenuComplete' The description of the current selected value will be displayed below the suggestions.
+$ helm s[tab]
+search show status
+
+search for a keyword in charts
+
+# Without descriptions
+$ helm s[tab]
+search show status
+```
+
+### Limitations
+
+* Custom completions implemented in bash scripting (legacy) are not supported and will be ignored for `powershell` (including the use of the `BashCompCustom` flag annotation).
+ * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`).
+* The function `MarkFlagCustom()` is not supported and will be ignored for `powershell`.
+ * You should instead use `RegisterFlagCompletionFunc()`.
+* The following flag completion annotations are not supported and will be ignored for `powershell`:
+ * `BashCompFilenameExt` (filtering by file extension)
+ * `BashCompSubdirsInDir` (filtering by directory)
+* The functions corresponding to the above annotations are consequently not supported and will be ignored for `powershell`:
+ * `MarkFlagFilename()` and `MarkPersistentFlagFilename()` (filtering by file extension)
+ * `MarkFlagDirname()` and `MarkPersistentFlagDirname()` (filtering by directory)
+* Similarly, the following completion directives are not supported and will be ignored for `powershell`:
+ * `ShellCompDirectiveFilterFileExt` (filtering by file extension)
+ * `ShellCompDirectiveFilterDirs` (filtering by directory)
diff --git a/vendor/github.com/spf13/cobra/zsh_completions.go b/vendor/github.com/spf13/cobra/zsh_completions.go
index 92a70394a..2e840285f 100644
--- a/vendor/github.com/spf13/cobra/zsh_completions.go
+++ b/vendor/github.com/spf13/cobra/zsh_completions.go
@@ -70,12 +70,12 @@ func (c *Command) genZshCompletion(w io.Writer, includeDesc bool) error {
return err
}
-func genZshComp(buf *bytes.Buffer, name string, includeDesc bool) {
+func genZshComp(buf io.StringWriter, name string, includeDesc bool) {
compCmd := ShellCompRequestCmd
if !includeDesc {
compCmd = ShellCompNoDescRequestCmd
}
- buf.WriteString(fmt.Sprintf(`#compdef _%[1]s %[1]s
+ WriteStringAndCheck(buf, fmt.Sprintf(`#compdef _%[1]s %[1]s
# zsh completion for %-36[1]s -*- shell-script -*-
diff --git a/vendor/gopkg.in/yaml.v2/.travis.yml b/vendor/gopkg.in/yaml.v2/.travis.yml
index 055480b9e..7348c50c0 100644
--- a/vendor/gopkg.in/yaml.v2/.travis.yml
+++ b/vendor/gopkg.in/yaml.v2/.travis.yml
@@ -11,6 +11,7 @@ go:
- "1.11.x"
- "1.12.x"
- "1.13.x"
+ - "1.14.x"
- "tip"
go_import_path: gopkg.in/yaml.v2
diff --git a/vendor/gopkg.in/yaml.v2/apic.go b/vendor/gopkg.in/yaml.v2/apic.go
index d2c2308f1..acf71402c 100644
--- a/vendor/gopkg.in/yaml.v2/apic.go
+++ b/vendor/gopkg.in/yaml.v2/apic.go
@@ -79,6 +79,8 @@ func yaml_parser_set_encoding(parser *yaml_parser_t, encoding yaml_encoding_t) {
parser.encoding = encoding
}
+var disableLineWrapping = false
+
// Create a new emitter object.
func yaml_emitter_initialize(emitter *yaml_emitter_t) {
*emitter = yaml_emitter_t{
@@ -86,7 +88,9 @@ func yaml_emitter_initialize(emitter *yaml_emitter_t) {
raw_buffer: make([]byte, 0, output_raw_buffer_size),
states: make([]yaml_emitter_state_t, 0, initial_stack_size),
events: make([]yaml_event_t, 0, initial_queue_size),
- best_width: -1,
+ }
+ if disableLineWrapping {
+ emitter.best_width = -1
}
}
diff --git a/vendor/gopkg.in/yaml.v2/go.mod b/vendor/gopkg.in/yaml.v2/go.mod
index 1934e8769..2cbb85aea 100644
--- a/vendor/gopkg.in/yaml.v2/go.mod
+++ b/vendor/gopkg.in/yaml.v2/go.mod
@@ -1,5 +1,5 @@
-module "gopkg.in/yaml.v2"
+module gopkg.in/yaml.v2
-require (
- "gopkg.in/check.v1" v0.0.0-20161208181325-20d25e280405
-)
+go 1.15
+
+require gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405
diff --git a/vendor/gopkg.in/yaml.v2/yaml.go b/vendor/gopkg.in/yaml.v2/yaml.go
index 89650e293..30813884c 100644
--- a/vendor/gopkg.in/yaml.v2/yaml.go
+++ b/vendor/gopkg.in/yaml.v2/yaml.go
@@ -175,7 +175,7 @@ func unmarshal(in []byte, out interface{}, strict bool) (err error) {
// Zero valued structs will be omitted if all their public
// fields are zero, unless they implement an IsZero
// method (see the IsZeroer interface type), in which
-// case the field will be included if that method returns true.
+// case the field will be excluded if IsZero returns true.
//
// flow Marshal using a flow style (useful for structs,
// sequences and maps).
@@ -464,3 +464,15 @@ func isZero(v reflect.Value) bool {
}
return false
}
+
+// FutureLineWrap globally disables line wrapping when encoding long strings.
+// This is a temporary and thus deprecated method introduced to faciliate
+// migration towards v3, which offers more control of line lengths on
+// individual encodings, and has a default matching the behavior introduced
+// by this function.
+//
+// The default formatting of v2 was erroneously changed in v2.3.0 and reverted
+// in v2.4.0, at which point this function was introduced to help migration.
+func FutureLineWrap() {
+ disableLineWrapping = true
+}
diff --git a/vendor/modules.txt b/vendor/modules.txt
index 7c1eaf8df..1da22e159 100644
--- a/vendor/modules.txt
+++ b/vendor/modules.txt
@@ -534,7 +534,7 @@ github.com/seccomp/libseccomp-golang
# github.com/sirupsen/logrus v1.7.0
github.com/sirupsen/logrus
github.com/sirupsen/logrus/hooks/syslog
-# github.com/spf13/cobra v1.1.1
+# github.com/spf13/cobra v1.1.2
github.com/spf13/cobra
# github.com/spf13/pflag v1.0.5
github.com/spf13/pflag
@@ -772,7 +772,7 @@ gopkg.in/square/go-jose.v2/cipher
gopkg.in/square/go-jose.v2/json
# gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7
gopkg.in/tomb.v1
-# gopkg.in/yaml.v2 v2.3.0
+# gopkg.in/yaml.v2 v2.4.0
gopkg.in/yaml.v2
# gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776
gopkg.in/yaml.v3
diff --git a/version/version.go b/version/version.go
index 0bba0147b..520014bb7 100644
--- a/version/version.go
+++ b/version/version.go
@@ -8,7 +8,7 @@ import (
// NOTE: remember to bump the version at the top
// of the top-level README.md file when this is
// bumped.
-var Version = semver.MustParse("3.0.0-dev")
+var Version = semver.MustParse("3.1.0-dev")
// APIVersion is the version for the remote
// client API. It is used to determine compatibility