From 25f5bb5f9702a947581857f29b1deab5a6dee921 Mon Sep 17 00:00:00 2001 From: Hugo Date: Sat, 14 May 2022 22:10:36 +0200 Subject: [PATCH 01/74] Prefer ReplaceAll instead of Replace(..., -1) (#1530) --- bash_completions.go | 6 +++--- doc/man_docs.go | 8 ++++---- doc/man_docs_test.go | 6 +++--- doc/md_docs.go | 6 +++--- doc/rest_docs.go | 8 ++++---- doc/yaml_docs.go | 2 +- fish_completions.go | 4 ++-- 7 files changed, 20 insertions(+), 20 deletions(-) diff --git a/bash_completions.go b/bash_completions.go index ff3f8f5e..3e1e5284 100644 --- a/bash_completions.go +++ b/bash_completions.go @@ -387,7 +387,7 @@ __%[1]s_handle_word() } func writePostscript(buf io.StringWriter, name string) { - name = strings.Replace(name, ":", "__", -1) + name = strings.ReplaceAll(name, ":", "__") WriteStringAndCheck(buf, fmt.Sprintf("__start_%s()\n", name)) WriteStringAndCheck(buf, fmt.Sprintf(`{ local cur prev words cword split @@ -645,8 +645,8 @@ func gen(buf io.StringWriter, cmd *Command) { gen(buf, c) } commandName := cmd.CommandPath() - commandName = strings.Replace(commandName, " ", "_", -1) - commandName = strings.Replace(commandName, ":", "__", -1) + commandName = strings.ReplaceAll(commandName, " ", "_") + commandName = strings.ReplaceAll(commandName, ":", "__") if cmd.Root() == cmd { WriteStringAndCheck(buf, fmt.Sprintf("_%s_root_command()\n{\n", commandName)) diff --git a/doc/man_docs.go b/doc/man_docs.go index 916e3614..8dbce35e 100644 --- a/doc/man_docs.go +++ b/doc/man_docs.go @@ -66,7 +66,7 @@ func GenManTreeFromOpts(cmd *cobra.Command, opts GenManTreeOptions) error { if opts.CommandSeparator != "" { separator = opts.CommandSeparator } - basename := strings.Replace(cmd.CommandPath(), " ", separator, -1) + basename := strings.ReplaceAll(cmd.CommandPath(), " ", separator) filename := filepath.Join(opts.Path, basename+"."+section) f, err := os.Create(filename) if err != nil { @@ -116,7 +116,7 @@ func GenMan(cmd *cobra.Command, header *GenManHeader, w io.Writer) error { func fillHeader(header *GenManHeader, name string, disableAutoGen bool) error { if header.Title == "" { - header.Title = strings.ToUpper(strings.Replace(name, " ", "\\-", -1)) + header.Title = strings.ToUpper(strings.ReplaceAll(name, " ", "\\-")) } if header.Section == "" { header.Section = "1" @@ -203,7 +203,7 @@ func genMan(cmd *cobra.Command, header *GenManHeader) []byte { cmd.InitDefaultHelpFlag() // something like `rootcmd-subcmd1-subcmd2` - dashCommandName := strings.Replace(cmd.CommandPath(), " ", "-", -1) + dashCommandName := strings.ReplaceAll(cmd.CommandPath(), " ", "-") buf := new(bytes.Buffer) @@ -218,7 +218,7 @@ func genMan(cmd *cobra.Command, header *GenManHeader) []byte { seealsos := make([]string, 0) if cmd.HasParent() { parentPath := cmd.Parent().CommandPath() - dashParentPath := strings.Replace(parentPath, " ", "-", -1) + dashParentPath := strings.ReplaceAll(parentPath, " ", "-") seealso := fmt.Sprintf("**%s(%s)**", dashParentPath, header.Section) seealsos = append(seealsos, seealso) cmd.VisitParents(func(c *cobra.Command) { diff --git a/doc/man_docs_test.go b/doc/man_docs_test.go index f3fe3d61..f7994f89 100644 --- a/doc/man_docs_test.go +++ b/doc/man_docs_test.go @@ -20,7 +20,7 @@ func assertNoErr(t *testing.T, e error) { } func translate(in string) string { - return strings.Replace(in, "-", "\\-", -1) + return strings.ReplaceAll(in, "-", "\\-") } func TestGenManDoc(t *testing.T) { @@ -38,7 +38,7 @@ func TestGenManDoc(t *testing.T) { // Make sure parent has - in CommandPath() in SEE ALSO: parentPath := echoCmd.Parent().CommandPath() - dashParentPath := strings.Replace(parentPath, " ", "-", -1) + dashParentPath := strings.ReplaceAll(parentPath, " ", "-") expected := translate(dashParentPath) expected = expected + "(" + header.Section + ")" checkStringContains(t, output, expected) @@ -73,7 +73,7 @@ func TestGenManNoHiddenParents(t *testing.T) { // Make sure parent has - in CommandPath() in SEE ALSO: parentPath := echoCmd.Parent().CommandPath() - dashParentPath := strings.Replace(parentPath, " ", "-", -1) + dashParentPath := strings.ReplaceAll(parentPath, " ", "-") expected := translate(dashParentPath) expected = expected + "(" + header.Section + ")" checkStringContains(t, output, expected) diff --git a/doc/md_docs.go b/doc/md_docs.go index 5181af8d..19d7e931 100644 --- a/doc/md_docs.go +++ b/doc/md_docs.go @@ -83,7 +83,7 @@ func GenMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) parent := cmd.Parent() pname := parent.CommandPath() link := pname + ".md" - link = strings.Replace(link, " ", "_", -1) + link = strings.ReplaceAll(link, " ", "_") buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", pname, linkHandler(link), parent.Short)) cmd.VisitParents(func(c *cobra.Command) { if c.DisableAutoGenTag { @@ -101,7 +101,7 @@ func GenMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) } cname := name + " " + child.Name() link := cname + ".md" - link = strings.Replace(link, " ", "_", -1) + link = strings.ReplaceAll(link, " ", "_") buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", cname, linkHandler(link), child.Short)) } buf.WriteString("\n") @@ -137,7 +137,7 @@ func GenMarkdownTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHa } } - basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".md" + basename := strings.ReplaceAll(cmd.CommandPath(), " ", "_") + ".md" filename := filepath.Join(dir, basename) f, err := os.Create(filename) if err != nil { diff --git a/doc/rest_docs.go b/doc/rest_docs.go index 051d8dc8..23dca16a 100644 --- a/doc/rest_docs.go +++ b/doc/rest_docs.go @@ -70,7 +70,7 @@ func GenReSTCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string, str if len(long) == 0 { long = short } - ref := strings.Replace(name, " ", "_", -1) + ref := strings.ReplaceAll(name, " ", "_") buf.WriteString(".. _" + ref + ":\n\n") buf.WriteString(name + "\n") @@ -99,7 +99,7 @@ func GenReSTCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string, str if cmd.HasParent() { parent := cmd.Parent() pname := parent.CommandPath() - ref = strings.Replace(pname, " ", "_", -1) + ref = strings.ReplaceAll(pname, " ", "_") buf.WriteString(fmt.Sprintf("* %s \t - %s\n", linkHandler(pname, ref), parent.Short)) cmd.VisitParents(func(c *cobra.Command) { if c.DisableAutoGenTag { @@ -116,7 +116,7 @@ func GenReSTCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string, str continue } cname := name + " " + child.Name() - ref = strings.Replace(cname, " ", "_", -1) + ref = strings.ReplaceAll(cname, " ", "_") buf.WriteString(fmt.Sprintf("* %s \t - %s\n", linkHandler(cname, ref), child.Short)) } buf.WriteString("\n") @@ -151,7 +151,7 @@ func GenReSTTreeCustom(cmd *cobra.Command, dir string, filePrepender func(string } } - basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".rst" + basename := strings.ReplaceAll(cmd.CommandPath(), " ", "_") + ".rst" filename := filepath.Join(dir, basename) f, err := os.Create(filename) if err != nil { diff --git a/doc/yaml_docs.go b/doc/yaml_docs.go index 96e6ad72..a79fa40e 100644 --- a/doc/yaml_docs.go +++ b/doc/yaml_docs.go @@ -66,7 +66,7 @@ func GenYamlTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandle } } - basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".yaml" + basename := strings.ReplaceAll(cmd.CommandPath(), " ", "_") + ".yaml" filename := filepath.Join(dir, basename) f, err := os.Create(filename) if err != nil { diff --git a/fish_completions.go b/fish_completions.go index bb57fd56..e14a06ea 100644 --- a/fish_completions.go +++ b/fish_completions.go @@ -11,8 +11,8 @@ import ( func genFishComp(buf io.StringWriter, name string, includeDesc bool) { // Variables should not contain a '-' or ':' character nameForVar := name - nameForVar = strings.Replace(nameForVar, "-", "_", -1) - nameForVar = strings.Replace(nameForVar, ":", "_", -1) + nameForVar = strings.ReplaceAll(nameForVar, "-", "_") + nameForVar = strings.ReplaceAll(nameForVar, ":", "_") compCmd := ShellCompRequestCmd if !includeDesc { From 8afe9d1b56f1c876f8f56ea91f838a30e01563de Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 14 May 2022 17:16:07 -0600 Subject: [PATCH 02/74] Bump github.com/cpuguy83/go-md2man/v2 from 2.0.1 to 2.0.2 (#1688) Bumps [github.com/cpuguy83/go-md2man/v2](https://github.com/cpuguy83/go-md2man) from 2.0.1 to 2.0.2. - [Release notes](https://github.com/cpuguy83/go-md2man/releases) - [Commits](https://github.com/cpuguy83/go-md2man/compare/v2.0.1...v2.0.2) --- updated-dependencies: - dependency-name: github.com/cpuguy83/go-md2man/v2 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 2d685591..1d45d9f9 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/spf13/cobra go 1.15 require ( - github.com/cpuguy83/go-md2man/v2 v2.0.1 + github.com/cpuguy83/go-md2man/v2 v2.0.2 github.com/inconshreveable/mousetrap v1.0.0 github.com/spf13/pflag v1.0.5 gopkg.in/yaml.v2 v2.4.0 diff --git a/go.sum b/go.sum index 6d534596..8ed22880 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,5 @@ -github.com/cpuguy83/go-md2man/v2 v2.0.1 h1:r/myEWzV9lfsM1tFLgDyu0atFtJ1fXn261LKYj/3DxU= -github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= +github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= From e1ded5cd9480aa9921a8cb0f646b6b569ac1b9d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Tue, 17 May 2022 20:47:47 +0300 Subject: [PATCH 03/74] fix(bash-v2): skip empty completions when filtering descriptions (#1691) `read` gives a last null value following a trailing newline. Regression from fb8031162c2ffab270774f13c6904bb04cbba5a7. --- bash_completionsV2.go | 1 + 1 file changed, 1 insertion(+) diff --git a/bash_completionsV2.go b/bash_completionsV2.go index 5e558a51..97202f1b 100644 --- a/bash_completionsV2.go +++ b/bash_completionsV2.go @@ -188,6 +188,7 @@ __%[1]s_handle_standard_completion_case() { local compline # Look for the longest completion so that we can format things nicely while IFS='' read -r compline; do + [[ -z $compline ]] && continue # Strip any description before checking the length comp=${compline%%%%$tab*} # Only consider the completions that match From ffa8860dbe017851bc4e8ff4fb2b6249cfc1e4d8 Mon Sep 17 00:00:00 2001 From: Andreas Deininger Date: Tue, 17 May 2022 20:28:13 +0200 Subject: [PATCH 04/74] Change links from http:// to https:// (#1695) --- README.md | 4 ++-- doc/md_docs.md | 2 +- doc/rest_docs.md | 2 +- doc/yaml_docs.md | 2 +- projects_using_cobra.md | 10 +++++----- user_guide.md | 6 +++--- 6 files changed, 13 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 55dc39d0..2bf15208 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Cobra is a library for creating powerful modern CLI applications. -Cobra is used in many Go projects such as [Kubernetes](http://kubernetes.io/), +Cobra is used in many Go projects such as [Kubernetes](https://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. @@ -28,7 +28,7 @@ Cobra provides: * Automatically generated man pages for your application * Command aliases so you can change things without breaking them * The flexibility to define your own help, usage, etc. -* Optional seamless integration with [viper](http://github.com/spf13/viper) for 12-factor apps +* Optional seamless integration with [viper](https://github.com/spf13/viper) for 12-factor apps # Concepts diff --git a/doc/md_docs.md b/doc/md_docs.md index 5c870625..1659175c 100644 --- a/doc/md_docs.md +++ b/doc/md_docs.md @@ -85,7 +85,7 @@ func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) } ``` -The `filePrepender` will prepend the return value given the full filepath to the rendered Markdown file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/): +The `filePrepender` will prepend the return value given the full filepath to the rendered Markdown file. A common use case is to add front matter to use the generated documentation with [Hugo](https://gohugo.io/): ```go const fmTemplate = `--- diff --git a/doc/rest_docs.md b/doc/rest_docs.md index 6098430e..3041c573 100644 --- a/doc/rest_docs.md +++ b/doc/rest_docs.md @@ -85,7 +85,7 @@ func GenReSTCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string, str } ``` -The `filePrepender` will prepend the return value given the full filepath to the rendered ReST file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/): +The `filePrepender` will prepend the return value given the full filepath to the rendered ReST file. A common use case is to add front matter to use the generated documentation with [Hugo](https://gohugo.io/): ```go const fmTemplate = `--- diff --git a/doc/yaml_docs.md b/doc/yaml_docs.md index 1a9b7c6a..172e61d1 100644 --- a/doc/yaml_docs.md +++ b/doc/yaml_docs.md @@ -82,7 +82,7 @@ func GenYamlCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) str } ``` -The `filePrepender` will prepend the return value given the full filepath to the rendered Yaml file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/): +The `filePrepender` will prepend the return value given the full filepath to the rendered Yaml file. A common use case is to add front matter to use the generated documentation with [Hugo](https://gohugo.io/): ```go const fmTemplate = `--- diff --git a/projects_using_cobra.md b/projects_using_cobra.md index 1d2266dc..4ac87d3c 100644 --- a/projects_using_cobra.md +++ b/projects_using_cobra.md @@ -1,8 +1,8 @@ ## Projects using Cobra - [Arduino CLI](https://github.com/arduino/arduino-cli) -- [Bleve](http://www.blevesearch.com/) -- [CockroachDB](http://www.cockroachlabs.com/) +- [Bleve](https://blevesearch.com/) +- [CockroachDB](https://www.cockroachlabs.com/) - [Cosmos SDK](https://github.com/cosmos/cosmos-sdk) - [Datree](https://github.com/datreeio/datree) - [Delve](https://github.com/derekparker/delve) @@ -14,14 +14,14 @@ - [Github CLI](https://github.com/cli/cli) - [GitHub Labeler](https://github.com/erdaltsksn/gh-label) - [Golangci-lint](https://golangci-lint.run) -- [GopherJS](http://www.gopherjs.org/) +- [GopherJS](https://github.com/gopherjs/gopherjs) - [GoReleaser](https://goreleaser.com) - [Helm](https://helm.sh) - [Hugo](https://gohugo.io) - [Infracost](https://github.com/infracost/infracost) - [Istio](https://istio.io) - [Kool](https://github.com/kool-dev/kool) -- [Kubernetes](http://kubernetes.io/) +- [Kubernetes](https://kubernetes.io/) - [Kubescape](https://github.com/armosec/kubescape) - [Linkerd](https://linkerd.io/) - [Mattermost-server](https://github.com/mattermost/mattermost-server) @@ -39,7 +39,7 @@ - [Pixie](https://github.com/pixie-io/pixie) - [Polygon Edge](https://github.com/0xPolygon/polygon-edge) - [Pouch](https://github.com/alibaba/pouch) -- [ProjectAtomic (enterprise)](http://www.projectatomic.io/) +- [ProjectAtomic (enterprise)](https://www.projectatomic.io/) - [Prototool](https://github.com/uber/prototool) - [QRcp](https://github.com/claudiodangelis/qrcp) - [Random](https://github.com/erdaltsksn/random) diff --git a/user_guide.md b/user_guide.md index 56a1e9c6..cde4032b 100644 --- a/user_guide.md +++ b/user_guide.md @@ -51,7 +51,7 @@ var rootCmd = &cobra.Command{ Short: "Hugo is a very fast static site generator", Long: `A Fast and Flexible Static Site Generator built with love by spf13 and friends in Go. - Complete documentation is available at http://hugo.spf13.com`, + Complete documentation is available at https://gohugo.io/documentation/`, Run: func(cmd *cobra.Command, args []string) { // Do Stuff Here }, @@ -429,7 +429,7 @@ a count and a string.`, } ``` -For a more complete example of a larger application, please checkout [Hugo](http://gohugo.io/). +For a more complete example of a larger application, please checkout [Hugo](https://gohugo.io/). ## Help Command @@ -627,7 +627,7 @@ Did you mean this? Run 'hugo --help' for usage. ``` -Suggestions are automatic based on every subcommand registered and use an implementation of [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion. +Suggestions are automatic based on every subcommand registered and use an implementation of [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion. If you need to disable suggestions or tweak the string distance in your command, use: From 5b11656e45a6a6579298a3b28c71f456ff196ad6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Wed, 18 May 2022 03:57:08 +0300 Subject: [PATCH 05/74] perf(bash-v2): read directly to COMPREPLY on descriptionless short circuit (#1700) Not that it'd really matter that much performancewise given the level we are at for this case, but this change makes the short circuit roughly twice as fast on my box as it was for the 1000 rounds done in marckhouzam/cobra-completion-testing. Perhaps more importantly, this makes the code arguably slightly cleaner. --- bash_completionsV2.go | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/bash_completionsV2.go b/bash_completionsV2.go index 97202f1b..e61e27c9 100644 --- a/bash_completionsV2.go +++ b/bash_completionsV2.go @@ -178,9 +178,7 @@ __%[1]s_handle_standard_completion_case() { # Short circuit to optimize if we don't have descriptions if [[ $out != *$tab* ]]; then - while IFS='' read -r comp; do - COMPREPLY+=("$comp") - done < <(IFS=$'\n' compgen -W "$out" -- "$cur") + IFS=$'\n' read -ra COMPREPLY -d '' < <(IFS=$'\n' compgen -W "$out" -- "$cur") return 0 fi From 37d481d4d40a07b1a8f2f6c345124540e870c85c Mon Sep 17 00:00:00 2001 From: Tom Payne Date: Sun, 5 Jun 2022 21:45:59 +0200 Subject: [PATCH 06/74] fix: Don't complete _command on zsh (#1690) Previously the generated zsh completion script started with the line #compdef _ where is the command that the zsh completion script is generated for. This enabled completions for both and _, but _ is the completion function itself and should not be completed. Furthermore, attempting to autocomplete _ (e.g. typing "_" in a zsh shell) causes zsh to hang. This commit fixes the #compdef line to only complete , not _. Co-authored-by: Arvid Norlander --- zsh_completions.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zsh_completions.go b/zsh_completions.go index c6048a9e..072921f9 100644 --- a/zsh_completions.go +++ b/zsh_completions.go @@ -75,7 +75,7 @@ func genZshComp(buf io.StringWriter, name string, includeDesc bool) { if !includeDesc { compCmd = ShellCompNoDescRequestCmd } - WriteStringAndCheck(buf, fmt.Sprintf(`#compdef _%[1]s %[1]s + WriteStringAndCheck(buf, fmt.Sprintf(`#compdef %[1]s # zsh completion for %-36[1]s -*- shell-script -*- From ca8e3c2779b8cc6168ab6ffdf9c1f2ac65652404 Mon Sep 17 00:00:00 2001 From: Ian Wahbe Date: Wed, 8 Jun 2022 14:12:54 -0700 Subject: [PATCH 07/74] Add Pulumi as a project using cobra (#1720) * Add Pulumi as a project using cobra --- projects_using_cobra.md | 1 + 1 file changed, 1 insertion(+) diff --git a/projects_using_cobra.md b/projects_using_cobra.md index 4ac87d3c..ac680118 100644 --- a/projects_using_cobra.md +++ b/projects_using_cobra.md @@ -41,6 +41,7 @@ - [Pouch](https://github.com/alibaba/pouch) - [ProjectAtomic (enterprise)](https://www.projectatomic.io/) - [Prototool](https://github.com/uber/prototool) +- [Pulumi](https://www.pulumi.com) - [QRcp](https://github.com/claudiodangelis/qrcp) - [Random](https://github.com/erdaltsksn/random) - [Rclone](https://rclone.org/) From 87ea1807f71dfa4d0bd7058c099b3978b128aea6 Mon Sep 17 00:00:00 2001 From: xuwu Date: Mon, 13 Jun 2022 10:22:49 +0800 Subject: [PATCH 08/74] Modify brew prefix path in macOS system (#1719) --- completions.go | 4 ++-- shell_completions.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/completions.go b/completions.go index ce1caab8..3de4e87a 100644 --- a/completions.go +++ b/completions.go @@ -652,7 +652,7 @@ To load completions for every new session, execute once: #### macOS: - %[1]s completion bash > /usr/local/etc/bash_completion.d/%[1]s + %[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s You will need to start a new shell for this setup to take effect. `, c.Root().Name()), @@ -689,7 +689,7 @@ To load completions for every new session, execute once: #### macOS: - %[1]s completion zsh > /usr/local/share/zsh/site-functions/_%[1]s + %[1]s completion zsh > $(brew --prefix)/share/zsh/site-functions/_%[1]s You will need to start a new shell for this setup to take effect. `, c.Root().Name()), diff --git a/shell_completions.md b/shell_completions.md index be17bf8c..1e2058ed 100644 --- a/shell_completions.md +++ b/shell_completions.md @@ -40,7 +40,7 @@ Bash: # Linux: $ %[1]s completion bash > /etc/bash_completion.d/%[1]s # macOS: - $ %[1]s completion bash > /usr/local/etc/bash_completion.d/%[1]s + $ %[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s Zsh: From 7dc8b004e653f2f69511378d52c2989c8f64d42b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 15 Jun 2022 16:08:55 -0600 Subject: [PATCH 09/74] Bump actions/setup-go from 2 to 3 (#1660) Bumps [actions/setup-go](https://github.com/actions/setup-go) from 2 to 3. - [Release notes](https://github.com/actions/setup-go/releases) - [Commits](https://github.com/actions/setup-go/compare/v2...v3) --- updated-dependencies: - dependency-name: actions/setup-go dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/test.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 0b3fb369..0c83f303 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -13,7 +13,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/setup-go@v2 + - uses: actions/setup-go@v3 with: go-version: '1.17' @@ -41,7 +41,7 @@ jobs: runs-on: ${{ matrix.platform }}-latest steps: - - uses: actions/setup-go@v2 + - uses: actions/setup-go@v3 with: go-version: 1.${{ matrix.go }}.x From f464d6c82e9af74b7a46301a775163984af32cd1 Mon Sep 17 00:00:00 2001 From: Marc Khouzam Date: Wed, 15 Jun 2022 20:08:16 -0400 Subject: [PATCH 10/74] Add Active Help support (#1482) --- active_help.go | 49 +++++ active_help.md | 157 +++++++++++++++ active_help_test.go | 386 +++++++++++++++++++++++++++++++++++++ bash_completions.go | 5 +- bash_completionsV2.go | 59 +++++- bash_completionsV2_test.go | 19 ++ bash_completions_test.go | 12 ++ completions.go | 6 + fish_completions.go | 5 +- fish_completions_test.go | 13 ++ power_completions_test.go | 19 ++ powershell_completions.go | 7 +- user_guide.md | 4 + zsh_completions.go | 31 ++- zsh_completions_test.go | 19 ++ 15 files changed, 776 insertions(+), 15 deletions(-) create mode 100644 active_help.go create mode 100644 active_help.md create mode 100644 active_help_test.go create mode 100644 bash_completionsV2_test.go create mode 100644 power_completions_test.go create mode 100644 zsh_completions_test.go diff --git a/active_help.go b/active_help.go new file mode 100644 index 00000000..0c631913 --- /dev/null +++ b/active_help.go @@ -0,0 +1,49 @@ +package cobra + +import ( + "fmt" + "os" + "strings" +) + +const ( + activeHelpMarker = "_activeHelp_ " + // The below values should not be changed: programs will be using them explicitly + // in their user documentation, and users will be using them explicitly. + activeHelpEnvVarSuffix = "_ACTIVE_HELP" + activeHelpGlobalEnvVar = "COBRA_ACTIVE_HELP" + activeHelpGlobalDisable = "0" +) + +// AppendActiveHelp adds the specified string to the specified array to be used as ActiveHelp. +// Such strings will be processed by the completion script and will be shown as ActiveHelp +// to the user. +// The array parameter should be the array that will contain the completions. +// This function can be called multiple times before and/or after completions are added to +// the array. Each time this function is called with the same array, the new +// ActiveHelp line will be shown below the previous ones when completion is triggered. +func AppendActiveHelp(compArray []string, activeHelpStr string) []string { + return append(compArray, fmt.Sprintf("%s%s", activeHelpMarker, activeHelpStr)) +} + +// GetActiveHelpConfig returns the value of the ActiveHelp environment variable +// _ACTIVE_HELP where is the name of the root command in upper +// case, with all - replaced by _. +// It will always return "0" if the global environment variable COBRA_ACTIVE_HELP +// is set to "0". +func GetActiveHelpConfig(cmd *Command) string { + activeHelpCfg := os.Getenv(activeHelpGlobalEnvVar) + if activeHelpCfg != activeHelpGlobalDisable { + activeHelpCfg = os.Getenv(activeHelpEnvVar(cmd.Root().Name())) + } + return activeHelpCfg +} + +// activeHelpEnvVar returns the name of the program-specific ActiveHelp environment +// variable. It has the format _ACTIVE_HELP where is the name of the +// root command in upper case, with all - replaced by _. +func activeHelpEnvVar(name string) string { + // This format should not be changed: users will be using it explicitly. + activeHelpEnvVar := strings.ToUpper(fmt.Sprintf("%s%s", name, activeHelpEnvVarSuffix)) + return strings.ReplaceAll(activeHelpEnvVar, "-", "_") +} diff --git a/active_help.md b/active_help.md new file mode 100644 index 00000000..5e7f59af --- /dev/null +++ b/active_help.md @@ -0,0 +1,157 @@ +# Active Help + +Active Help is a framework provided by Cobra which allows a program to define messages (hints, warnings, etc) that will be printed during program usage. It aims to make it easier for your users to learn how to use your program. If configured by the program, Active Help is printed when the user triggers shell completion. + +For example, +``` +bash-5.1$ helm repo add [tab] +You must choose a name for the repo you are adding. + +bash-5.1$ bin/helm package [tab] +Please specify the path to the chart to package + +bash-5.1$ bin/helm package [tab][tab] +bin/ internal/ scripts/ pkg/ testdata/ +``` + +**Hint**: A good place to use Active Help messages is when the normal completion system does not provide any suggestions. In such cases, Active Help nicely supplements the normal shell completions to guide the user in knowing what is expected by the program. +## Supported shells + +Active Help is currently only supported for the following shells: +- Bash (using [bash completion V2](shell_completions.md#bash-completion-v2) only). Note that bash 4.4 or higher is required for the prompt to appear when an Active Help message is printed. +- Zsh + +## Adding Active Help messages + +As Active Help uses the shell completion system, the implementation of Active Help messages is done by enhancing custom dynamic completions. If you are not familiar with dynamic completions, please refer to [Shell Completions](shell_completions.md). + +Adding Active Help is done through the use of the `cobra.AppendActiveHelp(...)` function, where the program repeatedly adds Active Help messages to the list of completions. Keep reading for details. + +### Active Help for nouns + +Adding Active Help when completing a noun is done within the `ValidArgsFunction(...)` of a command. Please notice the use of `cobra.AppendActiveHelp(...)` in the following example: + +```go +cmd := &cobra.Command{ + Use: "add [NAME] [URL]", + Short: "add a chart repository", + Args: require.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + return addRepo(args) + }, + ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + var comps []string + if len(args) == 0 { + comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding") + } else if len(args) == 1 { + comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding") + } else { + comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments") + } + return comps, cobra.ShellCompDirectiveNoFileComp + }, +} +``` +The example above defines the completions (none, in this specific example) as well as the Active Help messages for the `helm repo add` command. It yields the following behavior: +``` +bash-5.1$ helm repo add [tab] +You must choose a name for the repo you are adding + +bash-5.1$ helm repo add grafana [tab] +You must specify the URL for the repo you are adding + +bash-5.1$ helm repo add grafana https://grafana.github.io/helm-charts [tab] +This command does not take any more arguments +``` +**Hint**: As can be seen in the above example, a good place to use Active Help messages is when the normal completion system does not provide any suggestions. In such cases, Active Help nicely supplements the normal shell completions. + +### Active Help for flags + +Providing Active Help for flags is done in the same fashion as for nouns, but using the completion function registered for the flag. For example: +```go +_ = cmd.RegisterFlagCompletionFunc("version", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + if len(args) != 2 { + return cobra.AppendActiveHelp(nil, "You must first specify the chart to install before the --version flag can be completed"), cobra.ShellCompDirectiveNoFileComp + } + return compVersionFlag(args[1], toComplete) + }) +``` +The example above prints an Active Help message when not enough information was given by the user to complete the `--version` flag. +``` +bash-5.1$ bin/helm install myrelease --version 2.0.[tab] +You must first specify the chart to install before the --version flag can be completed + +bash-5.1$ bin/helm install myrelease bitnami/solr --version 2.0.[tab][tab] +2.0.1 2.0.2 2.0.3 +``` + +## User control of Active Help + +You may want to allow your users to disable Active Help or choose between different levels of Active Help. It is entirely up to the program to define the type of configurability of Active Help that it wants to offer, if any. +Allowing to configure Active Help is entirely optional; you can use Active Help in your program without doing anything about Active Help configuration. + +The way to configure Active Help is to use the program's Active Help environment +variable. That variable is named `_ACTIVE_HELP` where `` is the name of your +program in uppercase with any `-` replaced by an `_`. The variable should be set by the user to whatever +Active Help configuration values are supported by the program. + +For example, say `helm` has chosen to support three levels for Active Help: `on`, `off`, `local`. Then a user +would set the desired behavior to `local` by doing `export HELM_ACTIVE_HELP=local` in their shell. + +For simplicity, when in `cmd.ValidArgsFunction(...)` or a flag's completion function, the program should read the +Active Help configuration using the `cobra.GetActiveHelpConfig(cmd)` function and select what Active Help messages +should or should not be added (instead of reading the environment variable directly). + +For example: +```go +ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + activeHelpLevel := cobra.GetActiveHelpConfig(cmd) + + var comps []string + if len(args) == 0 { + if activeHelpLevel != "off" { + comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding") + } + } else if len(args) == 1 { + if activeHelpLevel != "off" { + comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding") + } + } else { + if activeHelpLevel == "local" { + comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments") + } + } + return comps, cobra.ShellCompDirectiveNoFileComp +}, +``` +**Note 1**: If the `_ACTIVE_HELP` environment variable is set to the string "0", Cobra will automatically disable all Active Help output (even if some output was specified by the program using the `cobra.AppendActiveHelp(...)` function). Using "0" can simplify your code in situations where you want to blindly disable Active Help without having to call `cobra.GetActiveHelpConfig(cmd)` explicitly. + +**Note 2**: If a user wants to disable Active Help for every single program based on Cobra, she can set the environment variable `COBRA_ACTIVE_HELP` to "0". In this case `cobra.GetActiveHelpConfig(cmd)` will return "0" no matter what the variable `_ACTIVE_HELP` is set to. + +**Note 3**: If the user does not set `_ACTIVE_HELP` or `COBRA_ACTIVE_HELP` (which will be a common case), the default value for the Active Help configuration returned by `cobra.GetActiveHelpConfig(cmd)` will be the empty string. +## Active Help with Cobra's default completion command + +Cobra provides a default `completion` command for programs that wish to use it. +When using the default `completion` command, Active Help is configurable in the same +fashion as described above using environment variables. You may wish to document this in more +details for your users. + +## Debugging Active Help + +Debugging your Active Help code is done in the same way as debugging your dynamic completion code, which is with Cobra's hidden `__complete` command. Please refer to [debugging shell completion](shell_completions.md#debugging) for details. + +When debugging with the `__complete` command, if you want to specify different Active Help configurations, you should use the active help environment variable. That variable is named `_ACTIVE_HELP` where any `-` is replaced by an `_`. For example, we can test deactivating some Active Help as shown below: +``` +$ HELM_ACTIVE_HELP=1 bin/helm __complete install wordpress bitnami/h +bitnami/haproxy +bitnami/harbor +_activeHelp_ WARNING: cannot re-use a name that is still in use +:0 +Completion ended with directive: ShellCompDirectiveDefault + +$ HELM_ACTIVE_HELP=0 bin/helm __complete install wordpress bitnami/h +bitnami/haproxy +bitnami/harbor +:0 +Completion ended with directive: ShellCompDirectiveDefault +``` diff --git a/active_help_test.go b/active_help_test.go new file mode 100644 index 00000000..524be884 --- /dev/null +++ b/active_help_test.go @@ -0,0 +1,386 @@ +package cobra + +import ( + "fmt" + "os" + "strings" + "testing" +) + +const ( + activeHelpMessage = "This is an activeHelp message" + activeHelpMessage2 = "This is the rest of the activeHelp message" +) + +func TestActiveHelpAlone(t *testing.T) { + rootCmd := &Command{ + Use: "root", + Run: emptyRun, + } + + activeHelpFunc := func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { + comps := AppendActiveHelp(nil, activeHelpMessage) + return comps, ShellCompDirectiveDefault + } + + // Test that activeHelp can be added to a root command + rootCmd.ValidArgsFunction = activeHelpFunc + + output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + expected := strings.Join([]string{ + fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage), + ":0", + "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n") + + if output != expected { + t.Errorf("expected: %q, got: %q", expected, output) + } + + rootCmd.ValidArgsFunction = nil + + // Test that activeHelp can be added to a child command + childCmd := &Command{ + Use: "thechild", + Short: "The child command", + Run: emptyRun, + } + rootCmd.AddCommand(childCmd) + + childCmd.ValidArgsFunction = activeHelpFunc + + output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + expected = strings.Join([]string{ + fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage), + ":0", + "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n") + + if output != expected { + t.Errorf("expected: %q, got: %q", expected, output) + } +} + +func TestActiveHelpWithComps(t *testing.T) { + rootCmd := &Command{ + Use: "root", + Run: emptyRun, + } + + childCmd := &Command{ + Use: "thechild", + Short: "The child command", + Run: emptyRun, + } + rootCmd.AddCommand(childCmd) + + // Test that activeHelp can be added following other completions + childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { + comps := []string{"first", "second"} + comps = AppendActiveHelp(comps, activeHelpMessage) + return comps, ShellCompDirectiveDefault + } + + output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + expected := strings.Join([]string{ + "first", + "second", + fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage), + ":0", + "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n") + + if output != expected { + t.Errorf("expected: %q, got: %q", expected, output) + } + + // Test that activeHelp can be added preceding other completions + childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { + var comps []string + comps = AppendActiveHelp(comps, activeHelpMessage) + comps = append(comps, []string{"first", "second"}...) + return comps, ShellCompDirectiveDefault + } + + output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + expected = strings.Join([]string{ + fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage), + "first", + "second", + ":0", + "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n") + + if output != expected { + t.Errorf("expected: %q, got: %q", expected, output) + } + + // Test that activeHelp can be added interleaved with other completions + childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { + comps := []string{"first"} + comps = AppendActiveHelp(comps, activeHelpMessage) + comps = append(comps, "second") + return comps, ShellCompDirectiveDefault + } + + output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + expected = strings.Join([]string{ + "first", + fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage), + "second", + ":0", + "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n") + + if output != expected { + t.Errorf("expected: %q, got: %q", expected, output) + } +} + +func TestMultiActiveHelp(t *testing.T) { + rootCmd := &Command{ + Use: "root", + Run: emptyRun, + } + + childCmd := &Command{ + Use: "thechild", + Short: "The child command", + Run: emptyRun, + } + rootCmd.AddCommand(childCmd) + + // Test that multiple activeHelp message can be added + childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { + comps := AppendActiveHelp(nil, activeHelpMessage) + comps = AppendActiveHelp(comps, activeHelpMessage2) + return comps, ShellCompDirectiveNoFileComp + } + + output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + expected := strings.Join([]string{ + fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage), + fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage2), + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n") + + if output != expected { + t.Errorf("expected: %q, got: %q", expected, output) + } + + // Test that multiple activeHelp messages can be used along with completions + childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { + comps := []string{"first"} + comps = AppendActiveHelp(comps, activeHelpMessage) + comps = append(comps, "second") + comps = AppendActiveHelp(comps, activeHelpMessage2) + return comps, ShellCompDirectiveNoFileComp + } + + output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + expected = strings.Join([]string{ + "first", + fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage), + "second", + fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage2), + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n") + + if output != expected { + t.Errorf("expected: %q, got: %q", expected, output) + } +} + +func TestActiveHelpForFlag(t *testing.T) { + rootCmd := &Command{ + Use: "root", + Run: emptyRun, + } + flagname := "flag" + rootCmd.Flags().String(flagname, "", "A flag") + + // Test that multiple activeHelp message can be added + _ = rootCmd.RegisterFlagCompletionFunc(flagname, func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { + comps := []string{"first"} + comps = AppendActiveHelp(comps, activeHelpMessage) + comps = append(comps, "second") + comps = AppendActiveHelp(comps, activeHelpMessage2) + return comps, ShellCompDirectiveNoFileComp + }) + + output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--flag", "") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + expected := strings.Join([]string{ + "first", + fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage), + "second", + fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage2), + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n") + + if output != expected { + t.Errorf("expected: %q, got: %q", expected, output) + } +} + +func TestConfigActiveHelp(t *testing.T) { + rootCmd := &Command{ + Use: "root", + Run: emptyRun, + } + + childCmd := &Command{ + Use: "thechild", + Short: "The child command", + Run: emptyRun, + } + rootCmd.AddCommand(childCmd) + + activeHelpCfg := "someconfig,anotherconfig" + // Set the variable that the user would be setting + os.Setenv(activeHelpEnvVar(rootCmd.Name()), activeHelpCfg) + + childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { + receivedActiveHelpCfg := GetActiveHelpConfig(cmd) + if receivedActiveHelpCfg != activeHelpCfg { + t.Errorf("expected activeHelpConfig: %q, but got: %q", activeHelpCfg, receivedActiveHelpCfg) + } + return nil, ShellCompDirectiveDefault + } + + _, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + // Test active help config for a flag + activeHelpCfg = "a config for a flag" + // Set the variable that the completions scripts will be setting + os.Setenv(activeHelpEnvVar(rootCmd.Name()), activeHelpCfg) + + flagname := "flag" + childCmd.Flags().String(flagname, "", "A flag") + + // Test that multiple activeHelp message can be added + _ = childCmd.RegisterFlagCompletionFunc(flagname, func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { + receivedActiveHelpCfg := GetActiveHelpConfig(cmd) + if receivedActiveHelpCfg != activeHelpCfg { + t.Errorf("expected activeHelpConfig: %q, but got: %q", activeHelpCfg, receivedActiveHelpCfg) + } + return nil, ShellCompDirectiveDefault + }) + + _, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "--flag", "") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } +} + +func TestDisableActiveHelp(t *testing.T) { + rootCmd := &Command{ + Use: "root", + Run: emptyRun, + } + + childCmd := &Command{ + Use: "thechild", + Short: "The child command", + Run: emptyRun, + } + rootCmd.AddCommand(childCmd) + + // Test the disabling of activeHelp using the specific program + // environment variable that the completions scripts will be setting. + // Make sure the disabling value is "0" by hard-coding it in the tests; + // this is for backwards-compatibility as programs will be using this value. + os.Setenv(activeHelpEnvVar(rootCmd.Name()), "0") + + childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { + comps := []string{"first"} + comps = AppendActiveHelp(comps, activeHelpMessage) + return comps, ShellCompDirectiveDefault + } + + output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + os.Unsetenv(activeHelpEnvVar(rootCmd.Name())) + + // Make sure there is no ActiveHelp in the output + expected := strings.Join([]string{ + "first", + ":0", + "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n") + + if output != expected { + t.Errorf("expected: %q, got: %q", expected, output) + } + + // Now test the global disabling of ActiveHelp + os.Setenv(activeHelpGlobalEnvVar, "0") + // Set the specific variable, to make sure it is ignored when the global env + // var is set properly + os.Setenv(activeHelpEnvVar(rootCmd.Name()), "1") + + output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + // Make sure there is no ActiveHelp in the output + expected = strings.Join([]string{ + "first", + ":0", + "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n") + + if output != expected { + t.Errorf("expected: %q, got: %q", expected, output) + } + + // Make sure that if the global env variable is set to anything else than + // the disable value it is ignored + os.Setenv(activeHelpGlobalEnvVar, "on") + // Set the specific variable, to make sure it is used (while ignoring the global env var) + activeHelpCfg := "1" + os.Setenv(activeHelpEnvVar(rootCmd.Name()), activeHelpCfg) + + childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { + receivedActiveHelpCfg := GetActiveHelpConfig(cmd) + if receivedActiveHelpCfg != activeHelpCfg { + t.Errorf("expected activeHelpConfig: %q, but got: %q", activeHelpCfg, receivedActiveHelpCfg) + } + return nil, ShellCompDirectiveDefault + } + + _, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } +} diff --git a/bash_completions.go b/bash_completions.go index 3e1e5284..cb7e1953 100644 --- a/bash_completions.go +++ b/bash_completions.go @@ -73,7 +73,8 @@ __%[1]s_handle_go_custom_completion() # Prepare the command to request completions for the program. # Calling ${words[0]} instead of directly %[1]s allows to handle aliases args=("${words[@]:1}") - requestComp="${words[0]} %[2]s ${args[*]}" + # Disable ActiveHelp which is not supported for bash completion v1 + requestComp="%[8]s=0 ${words[0]} %[2]s ${args[*]}" lastParam=${words[$((${#words[@]}-1))]} lastChar=${lastParam:$((${#lastParam}-1)):1} @@ -383,7 +384,7 @@ __%[1]s_handle_word() `, name, ShellCompNoDescRequestCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs)) + ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name))) } func writePostscript(buf io.StringWriter, name string) { diff --git a/bash_completionsV2.go b/bash_completionsV2.go index e61e27c9..d295791e 100644 --- a/bash_completionsV2.go +++ b/bash_completionsV2.go @@ -111,13 +111,18 @@ __%[1]s_process_completion_results() { fi fi + # Separate activeHelp from normal completions + local completions=() + local activeHelp=() + __%[1]s_extract_activeHelp + if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then # File extension filtering local fullFilter filter filteringCmd - # Do not use quotes around the $out variable or else newline + # Do not use quotes around the $completions variable or else newline # characters will be kept. - for filter in ${out}; do + for filter in ${completions[*]}; do fullFilter+="$filter|" done @@ -129,7 +134,7 @@ __%[1]s_process_completion_results() { # Use printf to strip any trailing newline local subdir - subdir=$(printf "%%s" "${out}") + subdir=$(printf "%%s" "${completions[0]}") if [ -n "$subdir" ]; then __%[1]s_debug "Listing directories in $subdir" pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return @@ -143,6 +148,43 @@ __%[1]s_process_completion_results() { __%[1]s_handle_special_char "$cur" : __%[1]s_handle_special_char "$cur" = + + # Print the activeHelp statements before we finish + if [ ${#activeHelp} -ne 0 ]; then + printf "\n"; + printf "%%s\n" "${activeHelp[@]}" + printf "\n" + + # The prompt format is only available from bash 4.4. + # We test if it is available before using it. + if (x=${PS1@P}) 2> /dev/null; then + printf "%%s" "${PS1@P}${COMP_LINE[@]}" + else + # Can't print the prompt. Just print the + # text the user had typed, it is workable enough. + printf "%%s" "${COMP_LINE[@]}" + fi + fi +} + +# Separate activeHelp lines from real completions. +# Fills the $activeHelp and $completions arrays. +__%[1]s_extract_activeHelp() { + local activeHelpMarker="%[8]s" + local endIndex=${#activeHelpMarker} + + while IFS='' read -r comp; do + if [ "${comp:0:endIndex}" = "$activeHelpMarker" ]; then + comp=${comp:endIndex} + __%[1]s_debug "ActiveHelp found: $comp" + if [ -n "$comp" ]; then + activeHelp+=("$comp") + fi + else + # Not an activeHelp line but a normal completion + completions+=("$comp") + fi + done < <(printf "%%s\n" "${out}") } __%[1]s_handle_completion_types() { @@ -163,7 +205,7 @@ __%[1]s_handle_completion_types() { if [[ $comp == "$cur"* ]]; then COMPREPLY+=("$comp") fi - done < <(printf "%%s\n" "${out}") + done < <(printf "%%s\n" "${completions[@]}") ;; *) @@ -177,8 +219,8 @@ __%[1]s_handle_standard_completion_case() { local tab=$'\t' comp # Short circuit to optimize if we don't have descriptions - if [[ $out != *$tab* ]]; then - IFS=$'\n' read -ra COMPREPLY -d '' < <(IFS=$'\n' compgen -W "$out" -- "$cur") + if [[ ${completions[*]} != *$tab* ]]; then + IFS=$'\n' read -ra COMPREPLY -d '' < <(compgen -W "${completions[*]}" -- "$cur") return 0 fi @@ -195,7 +237,7 @@ __%[1]s_handle_standard_completion_case() { if ((${#comp}>longest)); then longest=${#comp} fi - done < <(printf "%%s\n" "${out}") + done < <(printf "%%s\n" "${completions[@]}") # If there is a single completion left, remove the description text if [ ${#COMPREPLY[*]} -eq 1 ]; then @@ -305,7 +347,8 @@ fi # ex: ts=4 sw=4 et filetype=sh `, name, compCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs)) + ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, + activeHelpMarker)) } // GenBashCompletionFileV2 generates Bash completion version 2. diff --git a/bash_completionsV2_test.go b/bash_completionsV2_test.go new file mode 100644 index 00000000..a9a277ed --- /dev/null +++ b/bash_completionsV2_test.go @@ -0,0 +1,19 @@ +package cobra + +import ( + "bytes" + "fmt" + "testing" +) + +func TestBashCompletionV2WithActiveHelp(t *testing.T) { + c := &Command{Use: "c", Run: emptyRun} + + buf := new(bytes.Buffer) + assertNoErr(t, c.GenBashCompletionV2(buf, true)) + output := buf.String() + + // check that active help is not being disabled + activeHelpVar := activeHelpEnvVar(c.Name()) + checkOmit(t, output, fmt.Sprintf("%s=0", activeHelpVar)) +} diff --git a/bash_completions_test.go b/bash_completions_test.go index 21d1fe0e..6896e91c 100644 --- a/bash_completions_test.go +++ b/bash_completions_test.go @@ -261,3 +261,15 @@ func TestBashCompletionTraverseChildren(t *testing.T) { checkOmit(t, output, `local_nonpersistent_flags+=("--bool-flag")`) checkOmit(t, output, `local_nonpersistent_flags+=("-b")`) } + +func TestBashCompletionNoActiveHelp(t *testing.T) { + c := &Command{Use: "c", Run: emptyRun} + + buf := new(bytes.Buffer) + assertNoErr(t, c.GenBashCompletion(buf)) + output := buf.String() + + // check that active help is being disabled + activeHelpVar := activeHelpEnvVar(c.Name()) + check(t, output, fmt.Sprintf("%s=0", activeHelpVar)) +} diff --git a/completions.go b/completions.go index 3de4e87a..7a9a7fad 100644 --- a/completions.go +++ b/completions.go @@ -178,6 +178,12 @@ func (c *Command) initCompleteCmd(args []string) { noDescriptions := (cmd.CalledAs() == ShellCompNoDescRequestCmd) for _, comp := range completions { + if GetActiveHelpConfig(finalCmd) == activeHelpGlobalDisable { + // Remove all activeHelp entries in this case + if strings.HasPrefix(comp, activeHelpMarker) { + continue + } + } if noDescriptions { // Remove any description that may be included following a tab character. comp = strings.Split(comp, "\t")[0] diff --git a/fish_completions.go b/fish_completions.go index e14a06ea..005ee6be 100644 --- a/fish_completions.go +++ b/fish_completions.go @@ -38,7 +38,8 @@ function __%[1]s_perform_completion __%[1]s_debug "args: $args" __%[1]s_debug "last arg: $lastArg" - set -l requestComp "$args[1] %[3]s $args[2..-1] $lastArg" + # Disable ActiveHelp which is not supported for fish shell + set -l requestComp "%[9]s=0 $args[1] %[3]s $args[2..-1] $lastArg" __%[1]s_debug "Calling $requestComp" set -l results (eval $requestComp 2> /dev/null) @@ -196,7 +197,7 @@ complete -c %[2]s -n '__%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results' `, nameForVar, name, compCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs)) + ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name))) } // GenFishCompletion generates fish completion file and writes to the passed writer. diff --git a/fish_completions_test.go b/fish_completions_test.go index a3171e48..37091dcb 100644 --- a/fish_completions_test.go +++ b/fish_completions_test.go @@ -2,6 +2,7 @@ package cobra import ( "bytes" + "fmt" "testing" ) @@ -67,3 +68,15 @@ func TestProgWithColon(t *testing.T) { check(t, output, "-c root:colon") checkOmit(t, output, "-c root_colon") } + +func TestFishCompletionNoActiveHelp(t *testing.T) { + c := &Command{Use: "c", Run: emptyRun} + + buf := new(bytes.Buffer) + assertNoErr(t, c.GenFishCompletion(buf, true)) + output := buf.String() + + // check that active help is being disabled + activeHelpVar := activeHelpEnvVar(c.Name()) + check(t, output, fmt.Sprintf("%s=0", activeHelpVar)) +} diff --git a/power_completions_test.go b/power_completions_test.go new file mode 100644 index 00000000..77138359 --- /dev/null +++ b/power_completions_test.go @@ -0,0 +1,19 @@ +package cobra + +import ( + "bytes" + "fmt" + "testing" +) + +func TestPwshCompletionNoActiveHelp(t *testing.T) { + c := &Command{Use: "c", Run: emptyRun} + + buf := new(bytes.Buffer) + assertNoErr(t, c.GenPowerShellCompletion(buf)) + output := buf.String() + + // check that active help is being disabled + activeHelpVar := activeHelpEnvVar(c.Name()) + check(t, output, fmt.Sprintf("%s=0", activeHelpVar)) +} diff --git a/powershell_completions.go b/powershell_completions.go index 62d719f0..379e7c08 100644 --- a/powershell_completions.go +++ b/powershell_completions.go @@ -61,6 +61,7 @@ Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock { # 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" @@ -90,11 +91,13 @@ Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock { } __%[1]s_debug "Calling $RequestComp" + # First disable ActiveHelp which is not supported for Powershell + $env:%[8]s=0 + #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 "") { @@ -242,7 +245,7 @@ Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock { } `, name, compCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs)) + ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name))) } func (c *Command) genPowerShellCompletion(w io.Writer, includeDesc bool) error { diff --git a/user_guide.md b/user_guide.md index cde4032b..3a253de9 100644 --- a/user_guide.md +++ b/user_guide.md @@ -660,3 +660,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). + +## Providing Active Help + +Cobra makes use of the shell-completion system to define a framework allowing you to provide Active Help to your users. Active Help are messages (hints, warnings, etc) printed as the program is being used. Read more about it in [Active Help](active_help.md). diff --git a/zsh_completions.go b/zsh_completions.go index 072921f9..65cd94c6 100644 --- a/zsh_completions.go +++ b/zsh_completions.go @@ -163,7 +163,24 @@ _%[1]s() return fi + local activeHelpMarker="%[8]s" + local endIndex=${#activeHelpMarker} + local startIndex=$((${#activeHelpMarker}+1)) + local hasActiveHelp=0 while IFS='\n' read -r comp; do + # Check if this is an activeHelp statement (i.e., prefixed with $activeHelpMarker) + if [ "${comp[1,$endIndex]}" = "$activeHelpMarker" ];then + __%[1]s_debug "ActiveHelp found: $comp" + comp="${comp[$startIndex,-1]}" + if [ -n "$comp" ]; then + compadd -x "${comp}" + __%[1]s_debug "ActiveHelp will need delimiter" + hasActiveHelp=1 + fi + + continue + fi + if [ -n "$comp" ]; then # If requested, completions are returned with a description. # The description is preceded by a TAB character. @@ -180,6 +197,17 @@ _%[1]s() fi done < <(printf "%%s\n" "${out[@]}") + # Add a delimiter after the activeHelp statements, but only if: + # - there are completions following the activeHelp statements, or + # - file completion will be performed (so there will be choices after the activeHelp) + if [ $hasActiveHelp -eq 1 ]; then + if [ ${#completions} -ne 0 ] || [ $((directive & shellCompDirectiveNoFileComp)) -eq 0 ]; then + __%[1]s_debug "Adding activeHelp delimiter" + compadd -x "--" + hasActiveHelp=0 + fi + fi + if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then __%[1]s_debug "Activating nospace." noSpace="-S ''" @@ -254,5 +282,6 @@ if [ "$funcstack[1]" = "_%[1]s" ]; then fi `, name, compCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs)) + ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, + activeHelpMarker)) } diff --git a/zsh_completions_test.go b/zsh_completions_test.go new file mode 100644 index 00000000..b7addb4c --- /dev/null +++ b/zsh_completions_test.go @@ -0,0 +1,19 @@ +package cobra + +import ( + "bytes" + "fmt" + "testing" +) + +func TestZshCompletionWithActiveHelp(t *testing.T) { + c := &Command{Use: "c", Run: emptyRun} + + buf := new(bytes.Buffer) + assertNoErr(t, c.GenZshCompletion(buf)) + output := buf.String() + + // check that active help is not being disabled + activeHelpVar := activeHelpEnvVar(c.Name()) + checkOmit(t, output, fmt.Sprintf("%s=0", activeHelpVar)) +} From ed7bb9dda481082672ed9ea60c29b3b70ae0fc04 Mon Sep 17 00:00:00 2001 From: kida <42762517+t29kida@users.noreply.github.com> Date: Mon, 20 Jun 2022 11:38:49 +0900 Subject: [PATCH 11/74] Add unit test for fish completion (#1515) --- fish_completions_test.go | 56 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/fish_completions_test.go b/fish_completions_test.go index 37091dcb..381c6677 100644 --- a/fish_completions_test.go +++ b/fish_completions_test.go @@ -3,6 +3,8 @@ package cobra import ( "bytes" "fmt" + "log" + "os" "testing" ) @@ -80,3 +82,57 @@ func TestFishCompletionNoActiveHelp(t *testing.T) { activeHelpVar := activeHelpEnvVar(c.Name()) check(t, output, fmt.Sprintf("%s=0", activeHelpVar)) } + +func TestGenFishCompletionFile(t *testing.T) { + err := os.Mkdir("./tmp", 0755) + if err != nil { + log.Fatal(err.Error()) + } + + defer os.RemoveAll("./tmp") + + rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun} + child := &Command{ + Use: "child", + ValidArgsFunction: validArgsFunc, + Run: emptyRun, + } + rootCmd.AddCommand(child) + + assertNoErr(t, rootCmd.GenFishCompletionFile("./tmp/test", false)) +} + +func TestFailGenFishCompletionFile(t *testing.T) { + err := os.Mkdir("./tmp", 0755) + if err != nil { + log.Fatal(err.Error()) + } + + defer os.RemoveAll("./tmp") + + f, _ := os.OpenFile("./tmp/test", os.O_CREATE, 0400) + defer f.Close() + + rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun} + child := &Command{ + Use: "child", + ValidArgsFunction: validArgsFunc, + Run: emptyRun, + } + rootCmd.AddCommand(child) + + got := rootCmd.GenFishCompletionFile("./tmp/test", false) + if got == nil { + t.Error("should raise permission denied error") + } + + if os.Getenv("MSYSTEM") == "MINGW64" { + if got.Error() != "open ./tmp/test: Access is denied." { + t.Errorf("got: %s, want: %s", got.Error(), "open ./tmp/test: Access is denied.") + } + } else { + if got.Error() != "open ./tmp/test: permission denied" { + t.Errorf("got: %s, want: %s", got.Error(), "open ./tmp/test: permission denied") + } + } +} From 7c9831d376a6c048ae9f95b435cdde9dc14358a0 Mon Sep 17 00:00:00 2001 From: Marc Khouzam Date: Mon, 20 Jun 2022 00:11:21 -0400 Subject: [PATCH 12/74] Fix handling of descriptions for bash v3 (#1735) Fixes #1734 Tab characters that introduce completion descriptions weren't properly being handled with bash v3. This change fixes that. Signed-off-by: Marc Khouzam --- bash_completionsV2.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bash_completionsV2.go b/bash_completionsV2.go index d295791e..767bf031 100644 --- a/bash_completionsV2.go +++ b/bash_completionsV2.go @@ -219,7 +219,7 @@ __%[1]s_handle_standard_completion_case() { local tab=$'\t' comp # Short circuit to optimize if we don't have descriptions - if [[ ${completions[*]} != *$tab* ]]; then + if [[ "${completions[*]}" != *$tab* ]]; then IFS=$'\n' read -ra COMPREPLY -d '' < <(compgen -W "${completions[*]}" -- "$cur") return 0 fi From ea94a3db55f84f026891709d82ebf25e17f89e0d Mon Sep 17 00:00:00 2001 From: Unai Martinez-Corral <38422348+umarcor@users.noreply.github.com> Date: Tue, 21 Jun 2022 03:00:50 +0100 Subject: [PATCH 13/74] undefined or nil Args default to ArbitraryArgs (#1612) --- command.go | 2 +- user_guide.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/command.go b/command.go index 0f4511f3..3349be63 100644 --- a/command.go +++ b/command.go @@ -1012,7 +1012,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) { func (c *Command) ValidateArgs(args []string) error { if c.Args == nil { - return nil + return ArbitraryArgs(c, args) } return c.Args(c, args) } diff --git a/user_guide.md b/user_guide.md index 3a253de9..5a7acf88 100644 --- a/user_guide.md +++ b/user_guide.md @@ -326,8 +326,8 @@ In both of these cases: ## Positional and Custom Arguments -Validation of positional arguments can be specified using the `Args` field -of `Command`. +Validation of positional arguments can be specified using the `Args` field of `Command`. +If `Args` is undefined or `nil`, it defaults to `ArbitraryArgs`. The following validators are built in: From b9ca5949e2f58373e8e4c3823c213401f7d9d0e3 Mon Sep 17 00:00:00 2001 From: Paul Holzinger <45212748+Luap99@users.noreply.github.com> Date: Tue, 21 Jun 2022 04:02:33 +0200 Subject: [PATCH 14/74] use errors.Is() to check for errors (#1730) Since go 1.13 you can wrap errors. This make it no longer possible to compare with `==`, instead you have to compare with `errors.Is()`. I noticed this problem because -h was no longer working after I stared wrapping the errors in my custom FlagErrorFunc function. Note that this is only a problem when a custom help flag is defined. Signed-off-by: Paul Holzinger --- command.go | 3 ++- command_test.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/command.go b/command.go index 3349be63..675bb134 100644 --- a/command.go +++ b/command.go @@ -18,6 +18,7 @@ package cobra import ( "bytes" "context" + "errors" "fmt" "io" "os" @@ -990,7 +991,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) { if err != nil { // Always show help if requested, even if SilenceErrors is in // effect - if err == flag.ErrHelp { + if errors.Is(err, flag.ErrHelp) { cmd.HelpFunc()(cmd, args) return cmd, nil } diff --git a/command_test.go b/command_test.go index d48fef1a..0446e3c1 100644 --- a/command_test.go +++ b/command_test.go @@ -1723,6 +1723,38 @@ func TestFlagErrorFunc(t *testing.T) { } } +func TestFlagErrorFuncHelp(t *testing.T) { + c := &Command{Use: "c", Run: emptyRun} + c.PersistentFlags().Bool("help", false, "help for c") + c.SetFlagErrorFunc(func(_ *Command, err error) error { + return fmt.Errorf("wrap error: %w", err) + }) + + out, err := executeCommand(c, "--help") + if err != nil { + t.Errorf("--help should not fail: %v", err) + } + + expected := `Usage: + c [flags] + +Flags: + --help help for c +` + if out != expected { + t.Errorf("Expected: %v, got: %v", expected, out) + } + + out, err = executeCommand(c, "-h") + if err != nil { + t.Errorf("-h should not fail: %v", err) + } + + if out != expected { + t.Errorf("Expected: %v, got: %v", expected, out) + } +} + // TestSortedFlags checks, // if cmd.LocalFlags() is unsorted when cmd.Flags().SortFlags set to false. // Related to https://github.com/spf13/cobra/issues/404. From 5f2ec3c897155c3346e77430932e3966e5cfa648 Mon Sep 17 00:00:00 2001 From: Marc Khouzam Date: Mon, 20 Jun 2022 22:04:28 -0400 Subject: [PATCH 15/74] Update shell completion to respect flag groups (#1659) Signed-off-by: Marc Khouzam Co-authored-by: Marc Khouzam --- completions.go | 3 + completions_test.go | 186 ++++++++++++++++++++++++++++++++++++++++++++ flag_groups.go | 49 ++++++++++++ 3 files changed, 238 insertions(+) diff --git a/completions.go b/completions.go index 7a9a7fad..2c248399 100644 --- a/completions.go +++ b/completions.go @@ -325,6 +325,9 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi var completions []string var directive ShellCompDirective + // Enforce flag groups before doing flag completions + finalCmd.enforceFlagGroupsForCompletion() + // Note that we want to perform flagname completion even if finalCmd.DisableFlagParsing==true; // doing this allows for completion of persistent flag names even for commands that disable flag parsing. // diff --git a/completions_test.go b/completions_test.go index 28a3228e..fa087fd9 100644 --- a/completions_test.go +++ b/completions_test.go @@ -2691,3 +2691,189 @@ func TestFixedCompletions(t *testing.T) { t.Errorf("expected: %q, got: %q", expected, output) } } + +func TestCompletionForGroupedFlags(t *testing.T) { + getCmd := func() *Command { + rootCmd := &Command{ + Use: "root", + Run: emptyRun, + } + childCmd := &Command{ + Use: "child", + ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { + return []string{"subArg"}, ShellCompDirectiveNoFileComp + }, + Run: emptyRun, + } + rootCmd.AddCommand(childCmd) + + rootCmd.PersistentFlags().Int("ingroup1", -1, "ingroup1") + rootCmd.PersistentFlags().String("ingroup2", "", "ingroup2") + + childCmd.Flags().Bool("ingroup3", false, "ingroup3") + childCmd.Flags().Bool("nogroup", false, "nogroup") + + // Add flags to a group + childCmd.MarkFlagsRequiredTogether("ingroup1", "ingroup2", "ingroup3") + + return rootCmd + } + + // Each test case uses a unique command from the function above. + testcases := []struct { + desc string + args []string + expectedOutput string + }{ + { + desc: "flags in group not suggested without - prefix", + args: []string{"child", ""}, + expectedOutput: strings.Join([]string{ + "subArg", + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"), + }, + { + desc: "flags in group suggested with - prefix", + args: []string{"child", "-"}, + expectedOutput: strings.Join([]string{ + "--ingroup1", + "--ingroup2", + "--ingroup3", + "--nogroup", + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"), + }, + { + desc: "when flag in group present, other flags in group suggested even without - prefix", + args: []string{"child", "--ingroup2", "value", ""}, + expectedOutput: strings.Join([]string{ + "--ingroup1", + "--ingroup3", + "subArg", + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"), + }, + { + desc: "when all flags in group present, flags not suggested without - prefix", + args: []string{"child", "--ingroup1", "8", "--ingroup2", "value2", "--ingroup3", ""}, + expectedOutput: strings.Join([]string{ + "subArg", + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"), + }, + { + desc: "group ignored if some flags not applicable", + args: []string{"--ingroup2", "value", ""}, + expectedOutput: strings.Join([]string{ + "child", + "completion", + "help", + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"), + }, + } + + for _, tc := range testcases { + t.Run(tc.desc, func(t *testing.T) { + c := getCmd() + args := []string{ShellCompNoDescRequestCmd} + args = append(args, tc.args...) + output, err := executeCommand(c, args...) + switch { + case err == nil && output != tc.expectedOutput: + t.Errorf("expected: %q, got: %q", tc.expectedOutput, output) + case err != nil: + t.Errorf("Unexpected error %q", err) + } + }) + } +} + +func TestCompletionForMutuallyExclusiveFlags(t *testing.T) { + getCmd := func() *Command { + rootCmd := &Command{ + Use: "root", + Run: emptyRun, + } + childCmd := &Command{ + Use: "child", + ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { + return []string{"subArg"}, ShellCompDirectiveNoFileComp + }, + Run: emptyRun, + } + rootCmd.AddCommand(childCmd) + + rootCmd.PersistentFlags().IntSlice("ingroup1", []int{1}, "ingroup1") + rootCmd.PersistentFlags().String("ingroup2", "", "ingroup2") + + childCmd.Flags().Bool("ingroup3", false, "ingroup3") + childCmd.Flags().Bool("nogroup", false, "nogroup") + + // Add flags to a group + childCmd.MarkFlagsMutuallyExclusive("ingroup1", "ingroup2", "ingroup3") + + return rootCmd + } + + // Each test case uses a unique command from the function above. + testcases := []struct { + desc string + args []string + expectedOutput string + }{ + { + desc: "flags in mutually exclusive group not suggested without the - prefix", + args: []string{"child", ""}, + expectedOutput: strings.Join([]string{ + "subArg", + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"), + }, + { + desc: "flags in mutually exclusive group suggested with the - prefix", + args: []string{"child", "-"}, + expectedOutput: strings.Join([]string{ + "--ingroup1", + "--ingroup2", + "--ingroup3", + "--nogroup", + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"), + }, + { + desc: "when flag in mutually exclusive group present, other flags in group not suggested even with the - prefix", + args: []string{"child", "--ingroup1", "8", "-"}, + expectedOutput: strings.Join([]string{ + "--ingroup1", // Should be suggested again since it is a slice + "--nogroup", + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"), + }, + { + desc: "group ignored if some flags not applicable", + args: []string{"--ingroup1", "8", "-"}, + expectedOutput: strings.Join([]string{ + "--ingroup1", + "--ingroup2", + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"), + }, + } + + for _, tc := range testcases { + t.Run(tc.desc, func(t *testing.T) { + c := getCmd() + args := []string{ShellCompNoDescRequestCmd} + args = append(args, tc.args...) + output, err := executeCommand(c, args...) + switch { + case err == nil && output != tc.expectedOutput: + t.Errorf("expected: %q, got: %q", tc.expectedOutput, output) + case err != nil: + t.Errorf("Unexpected error %q", err) + } + }) + } +} diff --git a/flag_groups.go b/flag_groups.go index 1dba424a..dc784311 100644 --- a/flag_groups.go +++ b/flag_groups.go @@ -172,3 +172,52 @@ func sortedKeys(m map[string]map[string]bool) []string { sort.Strings(keys) return keys } + +// enforceFlagGroupsForCompletion will do the following: +// - when a flag in a group is present, other flags in the group will be marked required +// - when a flag in a mutually exclusive group is present, other flags in the group will be marked as hidden +// This allows the standard completion logic to behave appropriately for flag groups +func (c *Command) enforceFlagGroupsForCompletion() { + if c.DisableFlagParsing { + return + } + + flags := c.Flags() + groupStatus := map[string]map[string]bool{} + mutuallyExclusiveGroupStatus := map[string]map[string]bool{} + c.Flags().VisitAll(func(pflag *flag.Flag) { + processFlagForGroupAnnotation(flags, pflag, requiredAsGroup, groupStatus) + processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, mutuallyExclusiveGroupStatus) + }) + + // If a flag that is part of a group is present, we make all the other flags + // of that group required so that the shell completion suggests them automatically + for flagList, flagnameAndStatus := range groupStatus { + for _, isSet := range flagnameAndStatus { + if isSet { + // One of the flags of the group is set, mark the other ones as required + for _, fName := range strings.Split(flagList, " ") { + _ = c.MarkFlagRequired(fName) + } + } + } + } + + // If a flag that is mutually exclusive to others is present, we hide the other + // flags of that group so the shell completion does not suggest them + for flagList, flagnameAndStatus := range mutuallyExclusiveGroupStatus { + for flagName, isSet := range flagnameAndStatus { + if isSet { + // One of the flags of the mutually exclusive group is set, mark the other ones as hidden + // Don't mark the flag that is already set as hidden because it may be an + // array or slice flag and therefore must continue being suggested + for _, fName := range strings.Split(flagList, " ") { + if fName != flagName { + flag := c.Flags().Lookup(fName) + flag.Hidden = true + } + } + } + } + } +} From 06b06a9dc9f9f5eba93c552b2532a3da64ef9877 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 20 Jun 2022 20:06:17 -0600 Subject: [PATCH 16/74] Bump golangci/golangci-lint-action from 3.1.0 to 3.2.0 (#1697) Bumps [golangci/golangci-lint-action](https://github.com/golangci/golangci-lint-action) from 3.1.0 to 3.2.0. - [Release notes](https://github.com/golangci/golangci-lint-action/releases) - [Commits](https://github.com/golangci/golangci-lint-action/compare/v3.1.0...v3.2.0) --- updated-dependencies: - dependency-name: golangci/golangci-lint-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 0c83f303..0ca8367a 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -19,7 +19,7 @@ jobs: - uses: actions/checkout@v3 - - uses: golangci/golangci-lint-action@v3.1.0 + - uses: golangci/golangci-lint-action@v3.2.0 with: version: latest args: --verbose From 3d38d18a23b094d1fd08ea0c7b257704990ddecf Mon Sep 17 00:00:00 2001 From: Miguel Duarte Barroso Date: Thu, 23 Jun 2022 17:36:12 +0200 Subject: [PATCH 17/74] Add KubeVirt as a project using cobra (#1741) Reaching out on behalf of KubeVirt, an add-on for Kubernetes, enabling users to run Virtual Machines on Kubernetes pods. Signed-off-by: Miguel Duarte Barroso --- projects_using_cobra.md | 1 + 1 file changed, 1 insertion(+) diff --git a/projects_using_cobra.md b/projects_using_cobra.md index ac680118..39603321 100644 --- a/projects_using_cobra.md +++ b/projects_using_cobra.md @@ -23,6 +23,7 @@ - [Kool](https://github.com/kool-dev/kool) - [Kubernetes](https://kubernetes.io/) - [Kubescape](https://github.com/armosec/kubescape) +- [KubeVirt](https://github.com/kubevirt/kubevirt) - [Linkerd](https://linkerd.io/) - [Mattermost-server](https://github.com/mattermost/mattermost-server) - [Mercure](https://mercure.rocks/) From bba9331d4e5e5ebe2d0fdf0d9432b4b1e67d5061 Mon Sep 17 00:00:00 2001 From: Yevgeny Pats Date: Sat, 25 Jun 2022 19:17:06 +0300 Subject: [PATCH 18/74] doc: Add CloudQuery for projects using Cobra (#1742) --- projects_using_cobra.md | 1 + 1 file changed, 1 insertion(+) diff --git a/projects_using_cobra.md b/projects_using_cobra.md index 39603321..ab25112b 100644 --- a/projects_using_cobra.md +++ b/projects_using_cobra.md @@ -2,6 +2,7 @@ - [Arduino CLI](https://github.com/arduino/arduino-cli) - [Bleve](https://blevesearch.com/) +- [CloudQuery](https://github.com/cloudquery/cloudquery) - [CockroachDB](https://www.cockroachlabs.com/) - [Cosmos SDK](https://github.com/cosmos/cosmos-sdk) - [Datree](https://github.com/datreeio/datree) From 69083f81b225303d63c23e14f77e4f361c4cc792 Mon Sep 17 00:00:00 2001 From: Tobias Klauser Date: Tue, 28 Jun 2022 23:19:33 +0200 Subject: [PATCH 19/74] Add Cilium to projects using Cobra (#1745) --- projects_using_cobra.md | 1 + 1 file changed, 1 insertion(+) diff --git a/projects_using_cobra.md b/projects_using_cobra.md index ab25112b..91896620 100644 --- a/projects_using_cobra.md +++ b/projects_using_cobra.md @@ -2,6 +2,7 @@ - [Arduino CLI](https://github.com/arduino/arduino-cli) - [Bleve](https://blevesearch.com/) +- [Cilium](https://cilium.io/) - [CloudQuery](https://github.com/cloudquery/cloudquery) - [CockroachDB](https://www.cockroachlabs.com/) - [Cosmos SDK](https://github.com/cosmos/cosmos-sdk) From a0aadc68eb88af3acad9be0ec18c8b91438fd984 Mon Sep 17 00:00:00 2001 From: Ikko Ashimine Date: Thu, 7 Jul 2022 13:54:19 +0900 Subject: [PATCH 20/74] Spelling for GitHub CLI (#1744) --- README.md | 2 +- projects_using_cobra.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 2bf15208..a672c230 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ Cobra is a library for creating powerful modern CLI applications. Cobra is used in many Go projects such as [Kubernetes](https://kubernetes.io/), -[Hugo](https://gohugo.io), and [Github CLI](https://github.com/cli/cli) to +[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) diff --git a/projects_using_cobra.md b/projects_using_cobra.md index 91896620..dadfd24a 100644 --- a/projects_using_cobra.md +++ b/projects_using_cobra.md @@ -13,7 +13,7 @@ - [Gardener](https://github.com/gardener/gardenctl) - [Giant Swarm's gsctl](https://github.com/giantswarm/gsctl) - [Git Bump](https://github.com/erdaltsksn/git-bump) -- [Github CLI](https://github.com/cli/cli) +- [GitHub CLI](https://github.com/cli/cli) - [GitHub Labeler](https://github.com/erdaltsksn/gh-label) - [Golangci-lint](https://golangci-lint.run) - [GopherJS](https://github.com/gopherjs/gopherjs) From 162534f92f478e4af12e5d688615bb2c61fdb831 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20L=C3=B3pez=20Barba?= Date: Wed, 20 Jul 2022 15:45:07 +0200 Subject: [PATCH 21/74] doc: Add Okteto for projects using Cobra (#1759) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Javier López Barba --- projects_using_cobra.md | 1 + 1 file changed, 1 insertion(+) diff --git a/projects_using_cobra.md b/projects_using_cobra.md index dadfd24a..90296fe0 100644 --- a/projects_using_cobra.md +++ b/projects_using_cobra.md @@ -36,6 +36,7 @@ - [Multi-gitter](https://github.com/lindell/multi-gitter) - [Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack) - [nFPM](https://nfpm.goreleaser.com) +- [Okteto](https://github.com/okteto/okteto) - [OpenShift](https://www.openshift.com/) - [Ory Hydra](https://github.com/ory/hydra) - [Ory Kratos](https://github.com/ory/kratos) From 965924ac89db4eb3781bfe4b376474e60c788c20 Mon Sep 17 00:00:00 2001 From: Florian Forster Date: Thu, 4 Aug 2022 17:18:09 +0200 Subject: [PATCH 22/74] docs: add zitadel to the list (#1772) --- projects_using_cobra.md | 1 + 1 file changed, 1 insertion(+) diff --git a/projects_using_cobra.md b/projects_using_cobra.md index 90296fe0..b5b9dbf3 100644 --- a/projects_using_cobra.md +++ b/projects_using_cobra.md @@ -56,3 +56,4 @@ - [UpCloud CLI (`upctl`)](https://github.com/UpCloudLtd/upcloud-cli) - VMware's [Tanzu Community Edition](https://github.com/vmware-tanzu/community-edition) & [Tanzu Framework](https://github.com/vmware-tanzu/tanzu-framework) - [Werf](https://werf.io/) +- [ZITADEL](https://github.com/zitadel/zitadel) From 6bf8cd85825800c5cbc63009b1fb2c54185f05ed Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 13 Aug 2022 21:02:01 +0000 Subject: [PATCH 23/74] build(deps): bump github.com/inconshreveable/mousetrap (#1774) --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 1d45d9f9..a78cc5db 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.15 require ( github.com/cpuguy83/go-md2man/v2 v2.0.2 - github.com/inconshreveable/mousetrap v1.0.0 + github.com/inconshreveable/mousetrap v1.0.1 github.com/spf13/pflag v1.0.5 gopkg.in/yaml.v2 v2.4.0 ) diff --git a/go.sum b/go.sum index 8ed22880..2f5eab40 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,7 @@ github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= -github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= -github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= +github.com/inconshreveable/mousetrap v1.0.1 h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7Pgzkat/bFNc= +github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= From 7790bf97fd40e285913066cf65387ad281cd6c2e Mon Sep 17 00:00:00 2001 From: Zoran Regvart Date: Sat, 13 Aug 2022 23:31:45 +0200 Subject: [PATCH 24/74] fix: correct command path in see_also for YAML doc (#1771) The `see_also` section for child commands would include only the name of the commands. This adds the whole path, similar to how it's done for the other documentation formats. --- doc/yaml_docs.go | 2 +- doc/yaml_docs_test.go | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/doc/yaml_docs.go b/doc/yaml_docs.go index a79fa40e..3069b4ee 100644 --- a/doc/yaml_docs.go +++ b/doc/yaml_docs.go @@ -128,7 +128,7 @@ func GenYamlCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) str if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() { continue } - result = append(result, child.Name()+" - "+child.Short) + result = append(result, child.CommandPath()+" - "+child.Short) } yamlDoc.SeeAlso = result } diff --git a/doc/yaml_docs_test.go b/doc/yaml_docs_test.go index d08fa4f8..9bf5aa6c 100644 --- a/doc/yaml_docs_test.go +++ b/doc/yaml_docs_test.go @@ -2,6 +2,7 @@ package doc import ( "bytes" + "fmt" "io/ioutil" "os" "path/filepath" @@ -24,6 +25,7 @@ func TestGenYamlDoc(t *testing.T) { checkStringContains(t, output, "rootflag") checkStringContains(t, output, rootCmd.Short) checkStringContains(t, output, echoSubCmd.Short) + checkStringContains(t, output, fmt.Sprintf("- %s - %s", echoSubCmd.CommandPath(), echoSubCmd.Short)) } func TestGenYamlNoTag(t *testing.T) { From f911c0b89c6e0c41b6ad218c9235d8706c36a1b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Sun, 14 Aug 2022 00:44:47 +0300 Subject: [PATCH 25/74] fix(bash-v2): activeHelp length check syntax (#1762) ```shell $ set -u $ foo=() $ echo ${#foo} bash: foo: unbound variable echo ${#foo[*]} 0 ``` The above shows that an empty array needs the suffix `[*]` when checking its length, or else it is considered unbound. --- bash_completionsV2.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bash_completionsV2.go b/bash_completionsV2.go index 767bf031..351391af 100644 --- a/bash_completionsV2.go +++ b/bash_completionsV2.go @@ -150,7 +150,7 @@ __%[1]s_process_completion_results() { __%[1]s_handle_special_char "$cur" = # Print the activeHelp statements before we finish - if [ ${#activeHelp} -ne 0 ]; then + if [ ${#activeHelp[*]} -ne 0 ]; then printf "\n"; printf "%%s\n" "${activeHelp[@]}" printf "\n" From dbf85f6104904d539cabceebec234e817fa0df0c Mon Sep 17 00:00:00 2001 From: Tobias Klauser Date: Sun, 14 Aug 2022 00:18:46 +0200 Subject: [PATCH 26/74] Update gopkg.in/yaml.v2 to gopkg.in/yaml.v3 (#1766) API v3 was released in 2019 [1]. Update from the v2 API, no changes to the packages's use needed and no breaking changes expected. [1] https://ubuntu.com/blog/api-v3-of-the-yaml-package-for-go-is-available --- doc/yaml_docs.go | 2 +- go.mod | 2 +- go.sum | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/doc/yaml_docs.go b/doc/yaml_docs.go index 3069b4ee..784c3878 100644 --- a/doc/yaml_docs.go +++ b/doc/yaml_docs.go @@ -23,7 +23,7 @@ import ( "github.com/spf13/cobra" "github.com/spf13/pflag" - "gopkg.in/yaml.v2" + "gopkg.in/yaml.v3" ) type cmdOption struct { diff --git a/go.mod b/go.mod index a78cc5db..a1309e53 100644 --- a/go.mod +++ b/go.mod @@ -6,5 +6,5 @@ require ( github.com/cpuguy83/go-md2man/v2 v2.0.2 github.com/inconshreveable/mousetrap v1.0.1 github.com/spf13/pflag v1.0.5 - gopkg.in/yaml.v2 v2.4.0 + gopkg.in/yaml.v3 v3.0.1 ) diff --git a/go.sum b/go.sum index 2f5eab40..a8c544e2 100644 --- a/go.sum +++ b/go.sum @@ -8,5 +8,5 @@ github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -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.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= From 22b617914c8890ba20db7ceafcdc2ef4ca4817d3 Mon Sep 17 00:00:00 2001 From: Brian Pursley Date: Sun, 28 Aug 2022 12:46:39 -0400 Subject: [PATCH 27/74] fix: show flags that shadow parent persistent flag in child help (#1776) This fixes a bug where a child flag that shadows (has the same name as) a parent persistent flag would not be shown in the child command's help output and the parent flag would be shown instead under the global flags section. This change makes the help output consistent with the observed behavior during execution, where the child flag is the one that is actually used. --- command.go | 3 ++- command_test.go | 39 ++++++++++++++++++++++++++++++++++----- 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/command.go b/command.go index 675bb134..5fca7dc6 100644 --- a/command.go +++ b/command.go @@ -1505,7 +1505,8 @@ func (c *Command) LocalFlags() *flag.FlagSet { } addToLocal := func(f *flag.Flag) { - if c.lflags.Lookup(f.Name) == nil && c.parentsPflags.Lookup(f.Name) == nil { + // Add the flag if it is not a parent PFlag, or it shadows a parent PFlag + if c.lflags.Lookup(f.Name) == nil && f != c.parentsPflags.Lookup(f.Name) { c.lflags.AddFlag(f) } } diff --git a/command_test.go b/command_test.go index 0446e3c1..0b0b8213 100644 --- a/command_test.go +++ b/command_test.go @@ -707,10 +707,7 @@ func TestEmptyInputs(t *testing.T) { } } -func TestOverwrittenFlag(t *testing.T) { - // TODO: This test fails, but should work. - t.Skip() - +func TestChildFlagShadowsParentPersistentFlag(t *testing.T) { parent := &Command{Use: "parent", Run: emptyRun} child := &Command{Use: "child", Run: emptyRun} @@ -732,7 +729,7 @@ func TestOverwrittenFlag(t *testing.T) { } if childInherited.Lookup("intf") != nil { - t.Errorf(`InheritedFlags should not contain overwritten flag "intf"`) + t.Errorf(`InheritedFlags should not contain shadowed flag "intf"`) } if childLocal.Lookup("intf") == nil { t.Error(`LocalFlags expected to contain "intf", got "nil"`) @@ -887,6 +884,38 @@ func TestHelpCommandExecutedOnChild(t *testing.T) { checkStringContains(t, output, childCmd.Long) } +func TestHelpCommandExecutedOnChildWithFlagThatShadowsParentFlag(t *testing.T) { + parent := &Command{Use: "parent", Run: emptyRun} + child := &Command{Use: "child", Run: emptyRun} + parent.AddCommand(child) + + parent.PersistentFlags().Bool("foo", false, "parent foo usage") + parent.PersistentFlags().Bool("bar", false, "parent bar usage") + child.Flags().Bool("foo", false, "child foo usage") // This shadows parent's foo flag + child.Flags().Bool("baz", false, "child baz usage") + + got, err := executeCommand(parent, "help", "child") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + expected := `Usage: + parent child [flags] + +Flags: + --baz child baz usage + --foo child foo usage + -h, --help help for child + +Global Flags: + --bar parent bar usage +` + + if got != expected { + t.Errorf("Help text mismatch.\nExpected:\n%s\n\nGot:\n%s\n", expected, got) + } +} + func TestSetHelpCommand(t *testing.T) { c := &Command{Use: "c", Run: emptyRun} c.AddCommand(&Command{Use: "empty", Run: emptyRun}) From 704540525032e759304ffdbdacb2050dbdf4b2c5 Mon Sep 17 00:00:00 2001 From: Unai Martinez-Corral <38422348+umarcor@users.noreply.github.com> Date: Tue, 30 Aug 2022 02:35:16 +0100 Subject: [PATCH 28/74] ci: test on Golang 1.19 (#1782) * ci: test on Golang 1.19 * ci: run golangci-lint on golang 1.19 * Adds `check-latest` for setup-go action v3 * ci/golangci-lint: use latest version available in setup-go's manifest Signed-off-by: John McBride Signed-off-by: umarcor Co-authored-by: John McBride --- .github/workflows/test.yml | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 0ca8367a..e0c2f15c 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -15,7 +15,8 @@ jobs: - uses: actions/setup-go@v3 with: - go-version: '1.17' + go-version: '^1.19' + check-latest: true - uses: actions/checkout@v3 @@ -37,6 +38,7 @@ jobs: - 16 - 17 - 18 + - 19 name: '${{ matrix.platform }} | 1.${{ matrix.go }}.x' runs-on: ${{ matrix.platform }}-latest steps: @@ -56,8 +58,8 @@ jobs: - run: | export GOBIN=$HOME/go/bin case "${{ matrix.go }}" in - 16|17|18) _version='@latest';; - *) _version='';; + 14|15) _version='';; + *) _version='@latest';; esac go install github.com/kyoh86/richgo"${_version}" go install github.com/mitchellh/gox"${_version}" From 2a7647ff4661fd5bc54bdc022d349d7efe29674f Mon Sep 17 00:00:00 2001 From: Paul Meyer <49727155+katexochen@users.noreply.github.com> Date: Tue, 30 Aug 2022 04:12:56 +0200 Subject: [PATCH 29/74] Clarify SetContext documentation (#1748) --- command.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/command.go b/command.go index 5fca7dc6..6e611337 100644 --- a/command.go +++ b/command.go @@ -236,8 +236,8 @@ func (c *Command) Context() context.Context { return c.ctx } -// SetContext sets context for the command. It is set to context.Background by default and will be overwritten by -// Command.ExecuteContext or Command.ExecuteContextC +// SetContext sets context for the command. This context will be overwritten by +// Command.ExecuteContext or Command.ExecuteContextC. func (c *Command) SetContext(ctx context.Context) { c.ctx = ctx } From 0580724b5fe33fbbff193befb787b1a1a0fe36a0 Mon Sep 17 00:00:00 2001 From: Marc Khouzam Date: Tue, 30 Aug 2022 10:34:58 -0400 Subject: [PATCH 30/74] With go 1.18, we must use go install for a binary (#1726) The format "go install github.com/kyoh86/richgo@latest" will work with go 1.16 and higher. It will not work with go 1.15. However, since installing "richgo" is only required for people who want to run the go tests for the Cobra project itself, I feel it is ok to require go 1.16 or higher in this case. Signed-off-by: Marc Khouzam Signed-off-by: Marc Khouzam --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 443ef1a9..c433a01b 100644 --- a/Makefile +++ b/Makefile @@ -6,7 +6,7 @@ $(warning "could not find golangci-lint in $(PATH), run: curl -sfL https://insta endif ifeq (, $(shell which richgo)) -$(warning "could not find richgo in $(PATH), run: go get github.com/kyoh86/richgo") +$(warning "could not find richgo in $(PATH), run: go install github.com/kyoh86/richgo@latest") endif .PHONY: fmt lint test install_deps clean From 2e8ba6f3087bda425da42af31f7373cd2c2c08c5 Mon Sep 17 00:00:00 2001 From: John McBride Date: Wed, 7 Sep 2022 18:25:01 -0600 Subject: [PATCH 31/74] Use correct stale action `exempt-` yaml keys (#1800) Signed-off-by: John McBride --- .github/workflows/stale.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index a63518f6..8f8c7394 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -39,8 +39,8 @@ jobs: days-before-close: 30 stale-issue-label: 'lifecycle/stale' stale-pr-label: 'lifecycle/stale' - exempt-issue-label: 'lifecycle/frozen' - exempt-pr-label: 'lifecycle/frozen' + exempt-issue-labels: 'lifecycle/frozen' + exempt-pr-labels: 'lifecycle/frozen' close-issue-label: 'lifecycle/rotten' close-pr-label: 'lifecycle/rotten' From 70e53f62be77e03f376be845efacbd99c00024ca Mon Sep 17 00:00:00 2001 From: Unai Martinez-Corral <38422348+umarcor@users.noreply.github.com> Date: Sat, 10 Sep 2022 15:33:34 +0200 Subject: [PATCH 32/74] Deprecate ExactValidArgs() and test combinations of args validators (#1643) * deprecate ExactValidArgs in favour of MatchAll(OnlyValidArgs, ...) * test combinations of args validators * adjust docs --- args.go | 24 ++--- args_test.go | 250 +++++++++++++++++++++++++++++++++++++++++++++----- user_guide.md | 52 +++++++---- 3 files changed, 272 insertions(+), 54 deletions(-) diff --git a/args.go b/args.go index 20a022b3..e2f40d51 100644 --- a/args.go +++ b/args.go @@ -32,7 +32,8 @@ func NoArgs(cmd *Command, args []string) error { return nil } -// OnlyValidArgs returns an error if any args are not in the list of ValidArgs. +// OnlyValidArgs returns an error if there are any positional args that are not in +// the `ValidArgs` field of `Command` func OnlyValidArgs(cmd *Command, args []string) error { if len(cmd.ValidArgs) > 0 { // Remove any description that may be included in ValidArgs. @@ -41,7 +42,6 @@ func OnlyValidArgs(cmd *Command, args []string) error { for _, v := range cmd.ValidArgs { validArgs = append(validArgs, strings.Split(v, "\t")[0]) } - for _, v := range args { if !stringInSlice(v, validArgs) { return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(args[0])) @@ -86,18 +86,6 @@ func ExactArgs(n int) PositionalArgs { } } -// ExactValidArgs returns an error if -// there are not exactly N positional args OR -// there are any positional args that are not in the `ValidArgs` field of `Command` -func ExactValidArgs(n int) PositionalArgs { - return func(cmd *Command, args []string) error { - if err := ExactArgs(n)(cmd, args); err != nil { - return err - } - return OnlyValidArgs(cmd, args) - } -} - // RangeArgs returns an error if the number of args is not within the expected range. func RangeArgs(min int, max int) PositionalArgs { return func(cmd *Command, args []string) error { @@ -119,3 +107,11 @@ func MatchAll(pargs ...PositionalArgs) PositionalArgs { return nil } } + +// ExactValidArgs returns an error if there are not exactly N positional args OR +// there are any positional args that are not in the `ValidArgs` field of `Command` +// +// Deprecated: use MatchAll(ExactArgs(n), OnlyValidArgs) instead +func ExactValidArgs(n int) PositionalArgs { + return MatchAll(ExactArgs(n), OnlyValidArgs) +} diff --git a/args_test.go b/args_test.go index 6bd41c8f..ae4df2e2 100644 --- a/args_test.go +++ b/args_test.go @@ -27,7 +27,7 @@ func expectSuccess(output string, err error, t *testing.T) { } } -func validWithInvalidArgs(err error, t *testing.T) { +func validOnlyWithInvalidArgs(err error, t *testing.T) { if err == nil { t.Fatal("Expected an error") } @@ -38,12 +38,12 @@ func validWithInvalidArgs(err error, t *testing.T) { } } -func noArgsWithArgs(err error, t *testing.T) { +func noArgsWithArgs(err error, t *testing.T, arg string) { if err == nil { t.Fatal("Expected an error") } got := err.Error() - expected := `unknown command "illegal" for "c"` + expected := `unknown command "` + arg + `" for "c"` if got != expected { t.Errorf("Expected: %q, got: %q", expected, got) } @@ -93,102 +93,280 @@ func rangeArgsWithInvalidCount(err error, t *testing.T) { } } +// NoArgs + func TestNoArgs(t *testing.T) { c := getCommand(NoArgs, false) output, err := executeCommand(c) expectSuccess(output, err, t) } -func TestNoArgsWithArgs(t *testing.T) { +func TestNoArgs_WithArgs(t *testing.T) { c := getCommand(NoArgs, false) - _, err := executeCommand(c, "illegal") - noArgsWithArgs(err, t) + _, err := executeCommand(c, "one") + noArgsWithArgs(err, t, "one") } +func TestNoArgs_WithValid_WithArgs(t *testing.T) { + c := getCommand(NoArgs, true) + _, err := executeCommand(c, "one") + noArgsWithArgs(err, t, "one") +} + +func TestNoArgs_WithValid_WithInvalidArgs(t *testing.T) { + c := getCommand(NoArgs, true) + _, err := executeCommand(c, "a") + noArgsWithArgs(err, t, "a") +} + +func TestNoArgs_WithValidOnly_WithInvalidArgs(t *testing.T) { + c := getCommand(MatchAll(OnlyValidArgs, NoArgs), true) + _, err := executeCommand(c, "a") + validOnlyWithInvalidArgs(err, t) +} + +// OnlyValidArgs + func TestOnlyValidArgs(t *testing.T) { c := getCommand(OnlyValidArgs, true) output, err := executeCommand(c, "one", "two") expectSuccess(output, err, t) } -func TestOnlyValidArgsWithInvalidArgs(t *testing.T) { +func TestOnlyValidArgs_WithInvalidArgs(t *testing.T) { c := getCommand(OnlyValidArgs, true) _, err := executeCommand(c, "a") - validWithInvalidArgs(err, t) + validOnlyWithInvalidArgs(err, t) } +// ArbitraryArgs + func TestArbitraryArgs(t *testing.T) { c := getCommand(ArbitraryArgs, false) output, err := executeCommand(c, "a", "b") expectSuccess(output, err, t) } +func TestArbitraryArgs_WithValid(t *testing.T) { + c := getCommand(ArbitraryArgs, true) + output, err := executeCommand(c, "one", "two") + expectSuccess(output, err, t) +} + +func TestArbitraryArgs_WithValid_WithInvalidArgs(t *testing.T) { + c := getCommand(ArbitraryArgs, true) + output, err := executeCommand(c, "a") + expectSuccess(output, err, t) +} + +func TestArbitraryArgs_WithValidOnly_WithInvalidArgs(t *testing.T) { + c := getCommand(MatchAll(OnlyValidArgs, ArbitraryArgs), true) + _, err := executeCommand(c, "a") + validOnlyWithInvalidArgs(err, t) +} + +// MinimumNArgs + func TestMinimumNArgs(t *testing.T) { c := getCommand(MinimumNArgs(2), false) output, err := executeCommand(c, "a", "b", "c") expectSuccess(output, err, t) } -func TestMinimumNArgsWithLessArgs(t *testing.T) { +func TestMinimumNArgs_WithValid(t *testing.T) { + c := getCommand(MinimumNArgs(2), true) + output, err := executeCommand(c, "one", "three") + expectSuccess(output, err, t) +} + +func TestMinimumNArgs_WithValid__WithInvalidArgs(t *testing.T) { + c := getCommand(MinimumNArgs(2), true) + output, err := executeCommand(c, "a", "b") + expectSuccess(output, err, t) +} + +func TestMinimumNArgs_WithValidOnly_WithInvalidArgs(t *testing.T) { + c := getCommand(MatchAll(OnlyValidArgs, MinimumNArgs(2)), true) + _, err := executeCommand(c, "a", "b") + validOnlyWithInvalidArgs(err, t) +} + +func TestMinimumNArgs_WithLessArgs(t *testing.T) { c := getCommand(MinimumNArgs(2), false) _, err := executeCommand(c, "a") minimumNArgsWithLessArgs(err, t) } +func TestMinimumNArgs_WithLessArgs_WithValid(t *testing.T) { + c := getCommand(MinimumNArgs(2), true) + _, err := executeCommand(c, "one") + minimumNArgsWithLessArgs(err, t) +} + +func TestMinimumNArgs_WithLessArgs_WithValid_WithInvalidArgs(t *testing.T) { + c := getCommand(MinimumNArgs(2), true) + _, err := executeCommand(c, "a") + minimumNArgsWithLessArgs(err, t) +} + +func TestMinimumNArgs_WithLessArgs_WithValidOnly_WithInvalidArgs(t *testing.T) { + c := getCommand(MatchAll(OnlyValidArgs, MinimumNArgs(2)), true) + _, err := executeCommand(c, "a") + validOnlyWithInvalidArgs(err, t) +} + +// MaximumNArgs + func TestMaximumNArgs(t *testing.T) { c := getCommand(MaximumNArgs(3), false) output, err := executeCommand(c, "a", "b") expectSuccess(output, err, t) } -func TestMaximumNArgsWithMoreArgs(t *testing.T) { +func TestMaximumNArgs_WithValid(t *testing.T) { + c := getCommand(MaximumNArgs(2), true) + output, err := executeCommand(c, "one", "three") + expectSuccess(output, err, t) +} + +func TestMaximumNArgs_WithValid_WithInvalidArgs(t *testing.T) { + c := getCommand(MaximumNArgs(2), true) + output, err := executeCommand(c, "a", "b") + expectSuccess(output, err, t) +} + +func TestMaximumNArgs_WithValidOnly_WithInvalidArgs(t *testing.T) { + c := getCommand(MatchAll(OnlyValidArgs, MaximumNArgs(2)), true) + _, err := executeCommand(c, "a", "b") + validOnlyWithInvalidArgs(err, t) +} + +func TestMaximumNArgs_WithMoreArgs(t *testing.T) { c := getCommand(MaximumNArgs(2), false) _, err := executeCommand(c, "a", "b", "c") maximumNArgsWithMoreArgs(err, t) } +func TestMaximumNArgs_WithMoreArgs_WithValid(t *testing.T) { + c := getCommand(MaximumNArgs(2), true) + _, err := executeCommand(c, "one", "three", "two") + maximumNArgsWithMoreArgs(err, t) +} + +func TestMaximumNArgs_WithMoreArgs_WithValid_WithInvalidArgs(t *testing.T) { + c := getCommand(MaximumNArgs(2), true) + _, err := executeCommand(c, "a", "b", "c") + maximumNArgsWithMoreArgs(err, t) +} + +func TestMaximumNArgs_WithMoreArgs_WithValidOnly_WithInvalidArgs(t *testing.T) { + c := getCommand(MatchAll(OnlyValidArgs, MaximumNArgs(2)), true) + _, err := executeCommand(c, "a", "b", "c") + validOnlyWithInvalidArgs(err, t) +} + +// ExactArgs + func TestExactArgs(t *testing.T) { c := getCommand(ExactArgs(3), false) output, err := executeCommand(c, "a", "b", "c") expectSuccess(output, err, t) } -func TestExactArgsWithInvalidCount(t *testing.T) { +func TestExactArgs_WithValid(t *testing.T) { + c := getCommand(ExactArgs(3), true) + output, err := executeCommand(c, "three", "one", "two") + expectSuccess(output, err, t) +} + +func TestExactArgs_WithValid_WithInvalidArgs(t *testing.T) { + c := getCommand(ExactArgs(3), true) + output, err := executeCommand(c, "three", "a", "two") + expectSuccess(output, err, t) +} + +func TestExactArgs_WithValidOnly_WithInvalidArgs(t *testing.T) { + c := getCommand(MatchAll(OnlyValidArgs, ExactArgs(3)), true) + _, err := executeCommand(c, "three", "a", "two") + validOnlyWithInvalidArgs(err, t) +} + +func TestExactArgs_WithInvalidCount(t *testing.T) { c := getCommand(ExactArgs(2), false) _, err := executeCommand(c, "a", "b", "c") exactArgsWithInvalidCount(err, t) } -func TestExactValidArgs(t *testing.T) { - c := getCommand(ExactValidArgs(3), true) - output, err := executeCommand(c, "three", "one", "two") - expectSuccess(output, err, t) -} - -func TestExactValidArgsWithInvalidCount(t *testing.T) { - c := getCommand(ExactValidArgs(2), false) +func TestExactArgs_WithInvalidCount_WithValid(t *testing.T) { + c := getCommand(ExactArgs(2), true) _, err := executeCommand(c, "three", "one", "two") exactArgsWithInvalidCount(err, t) } -func TestExactValidArgsWithInvalidArgs(t *testing.T) { - c := getCommand(ExactValidArgs(3), true) +func TestExactArgs_WithInvalidCount_WithValid_WithInvalidArgs(t *testing.T) { + c := getCommand(ExactArgs(2), true) _, err := executeCommand(c, "three", "a", "two") - validWithInvalidArgs(err, t) + exactArgsWithInvalidCount(err, t) } +func TestExactArgs_WithInvalidCount_WithValidOnly_WithInvalidArgs(t *testing.T) { + c := getCommand(MatchAll(OnlyValidArgs, ExactArgs(2)), true) + _, err := executeCommand(c, "three", "a", "two") + validOnlyWithInvalidArgs(err, t) +} + +// RangeArgs + func TestRangeArgs(t *testing.T) { c := getCommand(RangeArgs(2, 4), false) output, err := executeCommand(c, "a", "b", "c") expectSuccess(output, err, t) } -func TestRangeArgsWithInvalidCount(t *testing.T) { +func TestRangeArgs_WithValid(t *testing.T) { + c := getCommand(RangeArgs(2, 4), true) + output, err := executeCommand(c, "three", "one", "two") + expectSuccess(output, err, t) +} + +func TestRangeArgs_WithValid_WithInvalidArgs(t *testing.T) { + c := getCommand(RangeArgs(2, 4), true) + output, err := executeCommand(c, "three", "a", "two") + expectSuccess(output, err, t) +} + +func TestRangeArgs_WithValidOnly_WithInvalidArgs(t *testing.T) { + c := getCommand(MatchAll(OnlyValidArgs, RangeArgs(2, 4)), true) + _, err := executeCommand(c, "three", "a", "two") + validOnlyWithInvalidArgs(err, t) +} + +func TestRangeArgs_WithInvalidCount(t *testing.T) { c := getCommand(RangeArgs(2, 4), false) _, err := executeCommand(c, "a") rangeArgsWithInvalidCount(err, t) } +func TestRangeArgs_WithInvalidCount_WithValid(t *testing.T) { + c := getCommand(RangeArgs(2, 4), true) + _, err := executeCommand(c, "two") + rangeArgsWithInvalidCount(err, t) +} + +func TestRangeArgs_WithInvalidCount_WithValid_WithInvalidArgs(t *testing.T) { + c := getCommand(RangeArgs(2, 4), true) + _, err := executeCommand(c, "a") + rangeArgsWithInvalidCount(err, t) +} + +func TestRangeArgs_WithInvalidCount_WithValidOnly_WithInvalidArgs(t *testing.T) { + c := getCommand(MatchAll(OnlyValidArgs, RangeArgs(2, 4)), true) + _, err := executeCommand(c, "a") + validOnlyWithInvalidArgs(err, t) +} + +// Takes(No)Args + func TestRootTakesNoArgs(t *testing.T) { rootCmd := &Command{Use: "root", Run: emptyRun} childCmd := &Command{Use: "child", Run: emptyRun} @@ -293,6 +471,32 @@ func TestMatchAll(t *testing.T) { } } +// DEPRECATED + +func TestExactValidArgs(t *testing.T) { + c := getCommand(ExactValidArgs(3), true) + output, err := executeCommand(c, "three", "one", "two") + expectSuccess(output, err, t) +} + +func TestExactValidArgs_WithInvalidCount(t *testing.T) { + c := getCommand(ExactValidArgs(2), false) + _, err := executeCommand(c, "three", "one", "two") + exactArgsWithInvalidCount(err, t) +} + +func TestExactValidArgs_WithInvalidCount_WithInvalidArgs(t *testing.T) { + c := getCommand(ExactValidArgs(2), true) + _, err := executeCommand(c, "three", "a", "two") + exactArgsWithInvalidCount(err, t) +} + +func TestExactValidArgs_WithInvalidArgs(t *testing.T) { + c := getCommand(ExactValidArgs(2), true) + _, err := executeCommand(c, "three", "a") + validOnlyWithInvalidArgs(err, t) +} + // This test make sure we keep backwards-compatibility with respect // to the legacyArgs() function. // It makes sure the root command accepts arguments if it does not have diff --git a/user_guide.md b/user_guide.md index 5a7acf88..6128ae46 100644 --- a/user_guide.md +++ b/user_guide.md @@ -302,15 +302,15 @@ rootCmd.MarkPersistentFlagRequired("region") ### Flag Groups -If you have different flags that must be provided together (e.g. if they provide the `--username` flag they MUST provide the `--password` flag as well) then +If you have different flags that must be provided together (e.g. if they provide the `--username` flag they MUST provide the `--password` flag as well) then Cobra can enforce that requirement: ```go rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)") rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)") rootCmd.MarkFlagsRequiredTogether("username", "password") -``` +``` -You can also prevent different flags from being provided together if they represent mutually +You can also prevent different flags from being provided together if they represent mutually exclusive options such as specifying an output format as either `--json` or `--yaml` but never both: ```go rootCmd.Flags().BoolVar(&u, "json", false, "Output in JSON") @@ -327,29 +327,47 @@ In both of these cases: ## Positional and Custom Arguments Validation of positional arguments can be specified using the `Args` field of `Command`. -If `Args` is undefined or `nil`, it defaults to `ArbitraryArgs`. - The following validators are built in: -- `NoArgs` - the command will report an error if there are any positional args. -- `ArbitraryArgs` - the command will accept any args. -- `OnlyValidArgs` - the command will report an error if there are any positional args that are not in the `ValidArgs` field of `Command`. -- `MinimumNArgs(int)` - the command will report an error if there are not at least N positional args. -- `MaximumNArgs(int)` - the command will report an error if there are more than N positional args. -- `ExactArgs(int)` - the command will report an error if there are not exactly N positional args. -- `ExactValidArgs(int)` - the command will report an error if there are not exactly N positional args OR if there are any positional args that are not in the `ValidArgs` field of `Command` -- `RangeArgs(min, max)` - the command will report an error if the number of args is not between the minimum and maximum number of expected args. -- `MatchAll(pargs ...PositionalArgs)` - enables combining existing checks with arbitrary other checks (e.g. you want to check the ExactArgs length along with other qualities). +- Number of arguments: + - `NoArgs` - report an error if there are any positional args. + - `ArbitraryArgs` - accept any number of args. + - `MinimumNArgs(int)` - report an error if less than N positional args are provided. + - `MaximumNArgs(int)` - report an error if more than N positional args are provided. + - `ExactArgs(int)` - report an error if there are not exactly N positional args. + - `RangeArgs(min, max)` - report an error if the number of args is not between `min` and `max`. +- Content of the arguments: + - `OnlyValidArgs` - report an error if there are any positional args not specified in the `ValidArgs` field of `Command`, which can optionally be set to a list of valid values for positional args. -An example of setting the custom validator: +If `Args` is undefined or `nil`, it defaults to `ArbitraryArgs`. + +Moreover, `MatchAll(pargs ...PositionalArgs)` enables combining existing checks with arbitrary other checks. +For instance, if you want to report an error if there are not exactly N positional args OR if there are any positional +args that are not in the `ValidArgs` field of `Command`, you can call `MatchAll` on `ExactArgs` and `OnlyValidArgs`, as +shown below: + +```go +var cmd = &cobra.Command{ + Short: "hello", + Args: MatchAll(ExactArgs(2), OnlyValidArgs), + Run: func(cmd *cobra.Command, args []string) { + fmt.Println("Hello, World!") + }, +} +``` + +It is possible to set any custom validator that satisfies `func(cmd *cobra.Command, args []string) error`. +For example: ```go var cmd = &cobra.Command{ Short: "hello", Args: func(cmd *cobra.Command, args []string) error { - if len(args) < 1 { - return errors.New("requires a color argument") + // Optionally run one of the validators provided by cobra + if err := cobra.MinimumNArgs(1)(cmd, args); err != nil { + return err } + // Run the custom validation logic if myapp.IsValidColor(args[0]) { return nil } From d689184a421607457a18131e0a2b602fec22e3b4 Mon Sep 17 00:00:00 2001 From: Yuval Goldberg Date: Sun, 11 Sep 2022 15:25:22 +0300 Subject: [PATCH 33/74] Support for case-insensitive command names (#1802) Add a global `EnableCaseInsensitive` variable to allow case-insensitive command names. The variable supports commands names and aliases globally. Resolves #1382 --- cobra.go | 13 +++++- command.go | 15 ++++++- command_test.go | 115 ++++++++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 135 insertions(+), 8 deletions(-) diff --git a/cobra.go b/cobra.go index d6cbfd71..e330f16b 100644 --- a/cobra.go +++ b/cobra.go @@ -40,14 +40,23 @@ var templateFuncs = template.FuncMap{ var initializers []func() +const ( + defaultPrefixMatching = false + defaultCommandSorting = true + defaultCaseInsensitive = false +) + // EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing // to automatically enable in CLI tools. // Set this to true to enable it. -var EnablePrefixMatching = false +var EnablePrefixMatching = defaultPrefixMatching // EnableCommandSorting controls sorting of the slice of commands, which is turned on by default. // To disable sorting, set it to false. -var EnableCommandSorting = true +var EnableCommandSorting = defaultCommandSorting + +// EnableCaseInsensitive allows case-insensitive commands names. (case sensitive by default) +var EnableCaseInsensitive = defaultCaseInsensitive // MousetrapHelpText enables an information splash screen on Windows // if the CLI is started from explorer.exe. diff --git a/command.go b/command.go index 6e611337..cc6f181d 100644 --- a/command.go +++ b/command.go @@ -676,7 +676,7 @@ func (c *Command) findSuggestions(arg string) string { func (c *Command) findNext(next string) *Command { matches := make([]*Command, 0) for _, cmd := range c.commands { - if cmd.Name() == next || cmd.HasAlias(next) { + if commandNameMatches(cmd.Name(), next) || cmd.HasAlias(next) { cmd.commandCalledAs.name = next return cmd } @@ -1328,7 +1328,7 @@ func (c *Command) Name() string { // HasAlias determines if a given string is an alias of the command. func (c *Command) HasAlias(s string) bool { for _, a := range c.Aliases { - if a == s { + if commandNameMatches(a, s) { return true } } @@ -1695,3 +1695,14 @@ func (c *Command) updateParentsPflags() { c.parentsPflags.AddFlagSet(parent.PersistentFlags()) }) } + +// commandNameMatches checks if two command names are equal +// taking into account case sensitivity according to +// EnableCaseInsensitive global configuration. +func commandNameMatches(s string, t string) bool { + if EnableCaseInsensitive { + return strings.EqualFold(s, t) + } + + return s == t +} diff --git a/command_test.go b/command_test.go index 0b0b8213..3f77d586 100644 --- a/command_test.go +++ b/command_test.go @@ -314,7 +314,7 @@ func TestEnablePrefixMatching(t *testing.T) { t.Errorf("aCmdArgs expected: %q, got: %q", onetwo, got) } - EnablePrefixMatching = false + EnablePrefixMatching = defaultPrefixMatching } func TestAliasPrefixMatching(t *testing.T) { @@ -349,7 +349,7 @@ func TestAliasPrefixMatching(t *testing.T) { t.Errorf("timesCmdArgs expected: %v, got: %v", onetwo, got) } - EnablePrefixMatching = false + EnablePrefixMatching = defaultPrefixMatching } // TestChildSameName checks the correct behaviour of cobra in cases, @@ -1263,6 +1263,113 @@ func TestSuggestions(t *testing.T) { } } +func TestCaseInsensitive(t *testing.T) { + rootCmd := &Command{Use: "root", Run: emptyRun} + childCmd := &Command{Use: "child", Run: emptyRun, Aliases: []string{"alternative"}} + granchildCmd := &Command{Use: "GRANDCHILD", Run: emptyRun, Aliases: []string{"ALIAS"}} + + childCmd.AddCommand(granchildCmd) + rootCmd.AddCommand(childCmd) + + tests := []struct { + args []string + failWithoutEnabling bool + }{ + { + args: []string{"child"}, + failWithoutEnabling: false, + }, + { + args: []string{"CHILD"}, + failWithoutEnabling: true, + }, + { + args: []string{"chILD"}, + failWithoutEnabling: true, + }, + { + args: []string{"CHIld"}, + failWithoutEnabling: true, + }, + { + args: []string{"alternative"}, + failWithoutEnabling: false, + }, + { + args: []string{"ALTERNATIVE"}, + failWithoutEnabling: true, + }, + { + args: []string{"ALTernatIVE"}, + failWithoutEnabling: true, + }, + { + args: []string{"alternatiVE"}, + failWithoutEnabling: true, + }, + { + args: []string{"child", "GRANDCHILD"}, + failWithoutEnabling: false, + }, + { + args: []string{"child", "grandchild"}, + failWithoutEnabling: true, + }, + { + args: []string{"CHIld", "GRANdchild"}, + failWithoutEnabling: true, + }, + { + args: []string{"alternative", "ALIAS"}, + failWithoutEnabling: false, + }, + { + args: []string{"alternative", "alias"}, + failWithoutEnabling: true, + }, + { + args: []string{"CHILD", "alias"}, + failWithoutEnabling: true, + }, + { + args: []string{"CHIld", "aliAS"}, + failWithoutEnabling: true, + }, + } + + for _, test := range tests { + for _, enableCaseInsensitivity := range []bool{true, false} { + EnableCaseInsensitive = enableCaseInsensitivity + + output, err := executeCommand(rootCmd, test.args...) + expectedFailure := test.failWithoutEnabling && !enableCaseInsensitivity + + if !expectedFailure && output != "" { + t.Errorf("Unexpected output: %v", output) + } + if !expectedFailure && err != nil { + t.Errorf("Unexpected error: %v", err) + } + } + } + + EnableCaseInsensitive = defaultCaseInsensitive +} + +// This test make sure we keep backwards-compatibility with respect +// to command names case sensitivity behavior. +func TestCaseSensitivityBackwardCompatibility(t *testing.T) { + rootCmd := &Command{Use: "root", Run: emptyRun} + childCmd := &Command{Use: "child", Run: emptyRun} + + rootCmd.AddCommand(childCmd) + _, err := executeCommand(rootCmd, strings.ToUpper(childCmd.Use)) + if err == nil { + t.Error("Expected error on calling a command in upper case while command names are case sensitive. Got nil.") + } + +} + func TestRemoveCommand(t *testing.T) { rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun} childCmd := &Command{Use: "child", Run: emptyRun} @@ -1622,7 +1729,7 @@ func TestCommandsAreSorted(t *testing.T) { } } - EnableCommandSorting = true + EnableCommandSorting = defaultCommandSorting } func TestEnableCommandSortingIsDisabled(t *testing.T) { @@ -1643,7 +1750,7 @@ func TestEnableCommandSortingIsDisabled(t *testing.T) { } } - EnableCommandSorting = true + EnableCommandSorting = defaultCommandSorting } func TestSetOutput(t *testing.T) { From fe08012eddbdf42edd466b8defeee33ec0ec4446 Mon Sep 17 00:00:00 2001 From: Marc Khouzam Date: Sun, 11 Sep 2022 17:04:53 -0400 Subject: [PATCH 34/74] Rename Powershell completion tests (#1803) The name of the powershell completion test file did not match the actual powershell file. Signed-off-by: Marc Khouzam --- power_completions_test.go => powershell_completions_test.go | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename power_completions_test.go => powershell_completions_test.go (100%) diff --git a/power_completions_test.go b/powershell_completions_test.go similarity index 100% rename from power_completions_test.go rename to powershell_completions_test.go From 7e289f46f1d1b2567b123cc26db0e7cd76644c32 Mon Sep 17 00:00:00 2001 From: Marc Khouzam Date: Sun, 11 Sep 2022 17:48:42 -0400 Subject: [PATCH 35/74] Adjustments to documentation (#1656) Signed-off-by: Marc Khouzam --- README.md | 4 ++-- user_guide.md | 27 +++++++++++++++------------ 2 files changed, 17 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index a672c230..08e4fa52 100644 --- a/README.md +++ b/README.md @@ -40,9 +40,9 @@ 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.` +`APPNAME VERB NOUN --ADJECTIVE` or -`APPNAME COMMAND ARG --FLAG` +`APPNAME COMMAND ARG --FLAG`. A few good real world examples may better illustrate this point. diff --git a/user_guide.md b/user_guide.md index 6128ae46..c694d871 100644 --- a/user_guide.md +++ b/user_guide.md @@ -462,28 +462,29 @@ create' is called. Every command will automatically have the '--help' flag adde The following output is automatically generated by Cobra. Nothing beyond the command and flag definitions are needed. - $ cobra help + $ cobra-cli help Cobra is a CLI library for Go that empowers applications. This application is a tool to generate the needed files to quickly create a Cobra application. Usage: - cobra [command] + cobra-cli [command] Available Commands: add Add a command to a Cobra Application + completion Generate the autocompletion script for the specified shell help Help about any command init Initialize a Cobra Application Flags: -a, --author string author name for copyright attribution (default "YOUR NAME") --config string config file (default is $HOME/.cobra.yaml) - -h, --help help for cobra + -h, --help help for cobra-cli -l, --license string name of license for the project - --viper use Viper for configuration (default true) + --viper use Viper for configuration - Use "cobra [command] --help" for more information about a command. + Use "cobra-cli [command] --help" for more information about a command. Help is just a command like any other. There is no special logic or behavior @@ -492,7 +493,7 @@ around it. In fact, you can provide your own if you want. ### Defining your own help You can provide your own Help command or your own template for the default command to use -with following functions: +with the following functions: ```go cmd.SetHelpCommand(cmd *Command) @@ -511,22 +512,23 @@ showing the user the 'usage'. You may recognize this from the help above. That's because the default help embeds the usage as part of its output. - $ cobra --invalid + $ cobra-cli --invalid Error: unknown flag: --invalid Usage: - cobra [command] + cobra-cli [command] Available Commands: add Add a command to a Cobra Application + completion Generate the autocompletion script for the specified shell help Help about any command init Initialize a Cobra Application Flags: -a, --author string author name for copyright attribution (default "YOUR NAME") --config string config file (default is $HOME/.cobra.yaml) - -h, --help help for cobra + -h, --help help for cobra-cli -l, --license string name of license for the project - --viper use Viper for configuration (default true) + --viper use Viper for configuration Use "cobra [command] --help" for more information about a command. @@ -645,7 +647,7 @@ Did you mean this? Run 'hugo --help' for usage. ``` -Suggestions are automatic based on every subcommand registered and use an implementation of [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion. +Suggestions are automatically generated based on existing subcommands and use an implementation of [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion. If you need to disable suggestions or tweak the string distance in your command, use: @@ -659,7 +661,8 @@ or command.SuggestionsMinimumDistance = 1 ``` -You can also explicitly set names for which a given command will be suggested using the `SuggestFor` attribute. This allows suggestions for strings that are not close in terms of string distance, but makes sense in your set of commands and for some which you don't want aliases. Example: +You can also explicitly set names for which a given command will be suggested using the `SuggestFor` attribute. This allows suggestions for strings that are not close in terms of string distance, but make sense in your set of commands but for which +you don't want aliases. Example: ``` $ kubectl remove From 4065a33bfdf697b6ce748a521686aee7edc748eb Mon Sep 17 00:00:00 2001 From: Unai Martinez-Corral <38422348+umarcor@users.noreply.github.com> Date: Wed, 14 Sep 2022 05:31:59 +0200 Subject: [PATCH 36/74] ci: use action/setup-go's cache (#1783) * ci: use action/setup-go's cache * ci: deprecate Golang 1.14 --- .github/workflows/test.yml | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index e0c2f15c..4e041c7f 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -13,10 +13,13 @@ jobs: runs-on: ubuntu-latest steps: + - uses: actions/checkout@v3 + - uses: actions/setup-go@v3 with: go-version: '^1.19' check-latest: true + cache: true - uses: actions/checkout@v3 @@ -33,7 +36,6 @@ jobs: - ubuntu - macOS go: - - 14 - 15 - 16 - 17 @@ -43,17 +45,12 @@ jobs: runs-on: ${{ matrix.platform }}-latest steps: + - uses: actions/checkout@v3 + - uses: actions/setup-go@v3 with: go-version: 1.${{ matrix.go }}.x - - - uses: actions/checkout@v3 - - - uses: actions/cache@v3 - with: - path: ~/go/pkg/mod - key: ${{ runner.os }}-1.${{ matrix.go }}.x-${{ hashFiles('**/go.sum') }} - restore-keys: ${{ runner.os }}-1.${{ matrix.go }}.x- + cache: true - run: | export GOBIN=$HOME/go/bin From 6d978a911e7fff69b1ca2a873dd91d78ebca44cf Mon Sep 17 00:00:00 2001 From: Unai Martinez-Corral <38422348+umarcor@users.noreply.github.com> Date: Fri, 16 Sep 2022 13:55:56 +0200 Subject: [PATCH 37/74] add missing license headers (#1809) --- .github/workflows/test.yml | 21 +++++++++++++++++++++ .golangci.yml | 14 ++++++++++++++ active_help.go | 14 ++++++++++++++ active_help_test.go | 14 ++++++++++++++ args.go | 14 ++++++++++++++ args_test.go | 14 ++++++++++++++ bash_completions.go | 14 ++++++++++++++ bash_completionsV2.go | 14 ++++++++++++++ bash_completionsV2_test.go | 14 ++++++++++++++ bash_completions_test.go | 14 ++++++++++++++ cobra.go | 5 +++-- cobra_test.go | 14 ++++++++++++++ command.go | 5 +++-- command_notwin.go | 14 ++++++++++++++ command_test.go | 14 ++++++++++++++ command_win.go | 14 ++++++++++++++ completions.go | 14 ++++++++++++++ completions_test.go | 14 ++++++++++++++ doc/cmd_test.go | 14 ++++++++++++++ doc/man_docs.go | 5 +++-- doc/man_docs_test.go | 14 ++++++++++++++ doc/man_examples_test.go | 14 ++++++++++++++ doc/md_docs.go | 5 +++-- doc/md_docs_test.go | 14 ++++++++++++++ doc/rest_docs.go | 5 +++-- doc/rest_docs_test.go | 14 ++++++++++++++ doc/util.go | 5 +++-- doc/yaml_docs.go | 5 +++-- doc/yaml_docs_test.go | 14 ++++++++++++++ fish_completions.go | 14 ++++++++++++++ fish_completions_test.go | 14 ++++++++++++++ flag_groups.go | 5 +++-- flag_groups_test.go | 5 +++-- powershell_completions.go | 14 ++++++++++++++ powershell_completions_test.go | 14 ++++++++++++++ shell_completions.go | 14 ++++++++++++++ zsh_completions.go | 14 ++++++++++++++ zsh_completions_test.go | 14 ++++++++++++++ 38 files changed, 440 insertions(+), 18 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 4e041c7f..797ae60e 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -9,6 +9,25 @@ env: jobs: + + lic-headers: + runs-on: ubuntu-latest + steps: + + - uses: actions/checkout@v3 + + - run: >- + docker run + -v $(pwd):/wrk -w /wrk + ghcr.io/google/addlicense + -c 'The Cobra Authors' + -y '2013-2022' + -l apache + -ignore '.github/**' + -check + . + + golangci-lint: runs-on: ubuntu-latest steps: @@ -28,6 +47,7 @@ jobs: version: latest args: --verbose + test-unix: strategy: fail-fast: false @@ -63,6 +83,7 @@ jobs: - run: RICHGO_FORCE_COLOR=1 PATH=$HOME/go/bin/:$PATH make test + test-win: name: MINGW64 defaults: diff --git a/.golangci.yml b/.golangci.yml index 0d6e6179..439d3e1d 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,3 +1,17 @@ +# Copyright 2013-2022 The Cobra Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + run: deadline: 5m diff --git a/active_help.go b/active_help.go index 0c631913..95e03aec 100644 --- a/active_help.go +++ b/active_help.go @@ -1,3 +1,17 @@ +// Copyright 2013-2022 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package cobra import ( diff --git a/active_help_test.go b/active_help_test.go index 524be884..3653dd87 100644 --- a/active_help_test.go +++ b/active_help_test.go @@ -1,3 +1,17 @@ +// Copyright 2013-2022 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package cobra import ( diff --git a/args.go b/args.go index e2f40d51..2c1f99e7 100644 --- a/args.go +++ b/args.go @@ -1,3 +1,17 @@ +// Copyright 2013-2022 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package cobra import ( diff --git a/args_test.go b/args_test.go index ae4df2e2..fd2c3b41 100644 --- a/args_test.go +++ b/args_test.go @@ -1,3 +1,17 @@ +// Copyright 2013-2022 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package cobra import ( diff --git a/bash_completions.go b/bash_completions.go index cb7e1953..3acdb279 100644 --- a/bash_completions.go +++ b/bash_completions.go @@ -1,3 +1,17 @@ +// Copyright 2013-2022 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package cobra import ( diff --git a/bash_completionsV2.go b/bash_completionsV2.go index 351391af..bb4b7189 100644 --- a/bash_completionsV2.go +++ b/bash_completionsV2.go @@ -1,3 +1,17 @@ +// Copyright 2013-2022 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package cobra import ( diff --git a/bash_completionsV2_test.go b/bash_completionsV2_test.go index a9a277ed..9302baf0 100644 --- a/bash_completionsV2_test.go +++ b/bash_completionsV2_test.go @@ -1,3 +1,17 @@ +// Copyright 2013-2022 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package cobra import ( diff --git a/bash_completions_test.go b/bash_completions_test.go index 6896e91c..5c32306d 100644 --- a/bash_completions_test.go +++ b/bash_completions_test.go @@ -1,3 +1,17 @@ +// Copyright 2013-2022 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package cobra import ( diff --git a/cobra.go b/cobra.go index e330f16b..1a95c3c1 100644 --- a/cobra.go +++ b/cobra.go @@ -1,9 +1,10 @@ -// Copyright © 2013 Steve Francia . +// Copyright 2013-2022 The Cobra Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 +// +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/cobra_test.go b/cobra_test.go index 1219cc07..71353c9d 100644 --- a/cobra_test.go +++ b/cobra_test.go @@ -1,3 +1,17 @@ +// Copyright 2013-2022 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package cobra import ( diff --git a/command.go b/command.go index cc6f181d..cdfd360f 100644 --- a/command.go +++ b/command.go @@ -1,9 +1,10 @@ -// Copyright © 2013 Steve Francia . +// Copyright 2013-2022 The Cobra Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 +// +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/command_notwin.go b/command_notwin.go index bb5dad90..2b77f8f0 100644 --- a/command_notwin.go +++ b/command_notwin.go @@ -1,3 +1,17 @@ +// Copyright 2013-2022 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + //go:build !windows // +build !windows diff --git a/command_test.go b/command_test.go index 3f77d586..a4b7366e 100644 --- a/command_test.go +++ b/command_test.go @@ -1,3 +1,17 @@ +// Copyright 2013-2022 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package cobra import ( diff --git a/command_win.go b/command_win.go index a84f5a82..520f23ab 100644 --- a/command_win.go +++ b/command_win.go @@ -1,3 +1,17 @@ +// Copyright 2013-2022 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + //go:build windows // +build windows diff --git a/completions.go b/completions.go index 2c248399..f8bf4f69 100644 --- a/completions.go +++ b/completions.go @@ -1,3 +1,17 @@ +// Copyright 2013-2022 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package cobra import ( diff --git a/completions_test.go b/completions_test.go index fa087fd9..c5f11fa5 100644 --- a/completions_test.go +++ b/completions_test.go @@ -1,3 +1,17 @@ +// Copyright 2013-2022 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package cobra import ( diff --git a/doc/cmd_test.go b/doc/cmd_test.go index 0917d602..4f2a0f58 100644 --- a/doc/cmd_test.go +++ b/doc/cmd_test.go @@ -1,3 +1,17 @@ +// Copyright 2013-2022 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package doc import ( diff --git a/doc/man_docs.go b/doc/man_docs.go index 8dbce35e..b5a2c596 100644 --- a/doc/man_docs.go +++ b/doc/man_docs.go @@ -1,9 +1,10 @@ -// Copyright 2015 Red Hat Inc. All rights reserved. +// Copyright 2013-2022 The Cobra Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 +// +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/doc/man_docs_test.go b/doc/man_docs_test.go index f7994f89..d296eebe 100644 --- a/doc/man_docs_test.go +++ b/doc/man_docs_test.go @@ -1,3 +1,17 @@ +// Copyright 2013-2022 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package doc import ( diff --git a/doc/man_examples_test.go b/doc/man_examples_test.go index e20a34c3..b995bf6d 100644 --- a/doc/man_examples_test.go +++ b/doc/man_examples_test.go @@ -1,3 +1,17 @@ +// Copyright 2013-2022 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package doc_test import ( diff --git a/doc/md_docs.go b/doc/md_docs.go index 19d7e931..bab4b496 100644 --- a/doc/md_docs.go +++ b/doc/md_docs.go @@ -1,9 +1,10 @@ -//Copyright 2015 Red Hat Inc. All rights reserved. +// Copyright 2013-2022 The Cobra Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 +// +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/doc/md_docs_test.go b/doc/md_docs_test.go index f3251679..b1632e9c 100644 --- a/doc/md_docs_test.go +++ b/doc/md_docs_test.go @@ -1,3 +1,17 @@ +// Copyright 2013-2022 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package doc import ( diff --git a/doc/rest_docs.go b/doc/rest_docs.go index 23dca16a..d6589065 100644 --- a/doc/rest_docs.go +++ b/doc/rest_docs.go @@ -1,9 +1,10 @@ -//Copyright 2015 Red Hat Inc. All rights reserved. +// Copyright 2013-2022 The Cobra Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 +// +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/doc/rest_docs_test.go b/doc/rest_docs_test.go index 330a2e5e..0c197f8d 100644 --- a/doc/rest_docs_test.go +++ b/doc/rest_docs_test.go @@ -1,3 +1,17 @@ +// Copyright 2013-2022 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package doc import ( diff --git a/doc/util.go b/doc/util.go index bffde94d..499ecdd9 100644 --- a/doc/util.go +++ b/doc/util.go @@ -1,9 +1,10 @@ -// Copyright 2015 Red Hat Inc. All rights reserved. +// Copyright 2013-2022 The Cobra Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 +// +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/doc/yaml_docs.go b/doc/yaml_docs.go index 784c3878..12f8cf33 100644 --- a/doc/yaml_docs.go +++ b/doc/yaml_docs.go @@ -1,9 +1,10 @@ -// Copyright 2016 French Ben. All rights reserved. +// Copyright 2013-2022 The Cobra Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 +// +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/doc/yaml_docs_test.go b/doc/yaml_docs_test.go index 9bf5aa6c..c552077d 100644 --- a/doc/yaml_docs_test.go +++ b/doc/yaml_docs_test.go @@ -1,3 +1,17 @@ +// Copyright 2013-2022 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package doc import ( diff --git a/fish_completions.go b/fish_completions.go index 005ee6be..97112a17 100644 --- a/fish_completions.go +++ b/fish_completions.go @@ -1,3 +1,17 @@ +// Copyright 2013-2022 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package cobra import ( diff --git a/fish_completions_test.go b/fish_completions_test.go index 381c6677..935f5540 100644 --- a/fish_completions_test.go +++ b/fish_completions_test.go @@ -1,3 +1,17 @@ +// Copyright 2013-2022 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package cobra import ( diff --git a/flag_groups.go b/flag_groups.go index dc784311..b09236fa 100644 --- a/flag_groups.go +++ b/flag_groups.go @@ -1,9 +1,10 @@ -// Copyright © 2022 Steve Francia . +// Copyright 2013-2022 The Cobra Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 +// +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/flag_groups_test.go b/flag_groups_test.go index 404ede56..b4b65ac0 100644 --- a/flag_groups_test.go +++ b/flag_groups_test.go @@ -1,9 +1,10 @@ -// Copyright © 2022 Steve Francia . +// Copyright 2013-2022 The Cobra Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 +// +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/powershell_completions.go b/powershell_completions.go index 379e7c08..351ded65 100644 --- a/powershell_completions.go +++ b/powershell_completions.go @@ -1,3 +1,17 @@ +// Copyright 2013-2022 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + // The generated scripts require PowerShell v5.0+ (which comes Windows 10, but // can be downloaded separately for windows 7 or 8.1). diff --git a/powershell_completions_test.go b/powershell_completions_test.go index 77138359..3d3d1033 100644 --- a/powershell_completions_test.go +++ b/powershell_completions_test.go @@ -1,3 +1,17 @@ +// Copyright 2013-2022 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package cobra import ( diff --git a/shell_completions.go b/shell_completions.go index d99bf91e..126e83c3 100644 --- a/shell_completions.go +++ b/shell_completions.go @@ -1,3 +1,17 @@ +// Copyright 2013-2022 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package cobra import ( diff --git a/zsh_completions.go b/zsh_completions.go index 65cd94c6..84cec76f 100644 --- a/zsh_completions.go +++ b/zsh_completions.go @@ -1,3 +1,17 @@ +// Copyright 2013-2022 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package cobra import ( diff --git a/zsh_completions_test.go b/zsh_completions_test.go index b7addb4c..258b1f71 100644 --- a/zsh_completions_test.go +++ b/zsh_completions_test.go @@ -1,3 +1,17 @@ +// Copyright 2013-2022 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package cobra import ( From 459fc5fce316465d5abc60faae27aa99687d62dc Mon Sep 17 00:00:00 2001 From: Unai Martinez-Corral <38422348+umarcor@users.noreply.github.com> Date: Fri, 16 Sep 2022 22:23:19 +0200 Subject: [PATCH 38/74] ci: add workflow_dispatch (#1387) --- .github/workflows/test.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 797ae60e..7865add6 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -3,6 +3,7 @@ name: Test on: push: pull_request: + workflow_dispatch: env: GO111MODULE: on From a281c8b47b315fe428cf31ad5c38b526dc136f55 Mon Sep 17 00:00:00 2001 From: Marc Khouzam Date: Fri, 16 Sep 2022 16:44:28 -0400 Subject: [PATCH 39/74] Document option to hide the default completion cmd (#1779) Signed-off-by: Marc Khouzam Signed-off-by: Marc Khouzam --- shell_completions.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/shell_completions.md b/shell_completions.md index 1e2058ed..a0957b4d 100644 --- a/shell_completions.md +++ b/shell_completions.md @@ -99,6 +99,11 @@ To tell Cobra *not* to provide the default `completion` command: rootCmd.CompletionOptions.DisableDefaultCmd = true ``` +To tell Cobra to mark the default `completion` command as *hidden*: +``` +rootCmd.CompletionOptions.HiddenDefaultCmd = true +``` + To tell Cobra *not* to provide the user with the `--no-descriptions` flag to the completion sub-commands: ``` rootCmd.CompletionOptions.DisableNoDescFlag = true From fce8d8aeb08dc6afe413cc0af67a7fbb3cffec4c Mon Sep 17 00:00:00 2001 From: Skeet WU Date: Tue, 27 Sep 2022 18:27:48 +0800 Subject: [PATCH 40/74] Expose ValidateRequiredFlags and ValidateFlagGroups (#1760) --- command.go | 7 ++++--- flag_groups.go | 4 ++-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/command.go b/command.go index cdfd360f..1867d22c 100644 --- a/command.go +++ b/command.go @@ -862,10 +862,10 @@ func (c *Command) execute(a []string) (err error) { c.PreRun(c, argWoFlags) } - if err := c.validateRequiredFlags(); err != nil { + if err := c.ValidateRequiredFlags(); err != nil { return err } - if err := c.validateFlagGroups(); err != nil { + if err := c.ValidateFlagGroups(); err != nil { return err } @@ -1019,7 +1019,8 @@ func (c *Command) ValidateArgs(args []string) error { return c.Args(c, args) } -func (c *Command) validateRequiredFlags() error { +// ValidateRequiredFlags validates all required flags are present and returns an error otherwise +func (c *Command) ValidateRequiredFlags() error { if c.DisableFlagParsing { return nil } diff --git a/flag_groups.go b/flag_groups.go index b09236fa..9c377aaf 100644 --- a/flag_groups.go +++ b/flag_groups.go @@ -59,9 +59,9 @@ func (c *Command) MarkFlagsMutuallyExclusive(flagNames ...string) { } } -// validateFlagGroups validates the mutuallyExclusive/requiredAsGroup logic and returns the +// ValidateFlagGroups validates the mutuallyExclusive/requiredAsGroup logic and returns the // first error encountered. -func (c *Command) validateFlagGroups() error { +func (c *Command) ValidateFlagGroups() error { if c.DisableFlagParsing { return nil } From 7039e1fa214cfc1de404ed6540158c8fda64a758 Mon Sep 17 00:00:00 2001 From: Francis Nickels III Date: Fri, 30 Sep 2022 11:26:05 -0700 Subject: [PATCH 41/74] Add '--version' flag to Help output (#1707) --- command.go | 3 +- command_test.go | 87 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 89 insertions(+), 1 deletion(-) diff --git a/command.go b/command.go index 1867d22c..5ed3df8d 100644 --- a/command.go +++ b/command.go @@ -1123,7 +1123,8 @@ Simply type ` + c.Name() + ` help [path to command] for full details.`, c.Printf("Unknown help topic %#q\n", args) CheckErr(c.Root().Usage()) } else { - cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown + cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown + cmd.InitDefaultVersionFlag() // make possible 'version' flag to be shown CheckErr(cmd.Help()) } }, diff --git a/command_test.go b/command_test.go index a4b7366e..b3dd0304 100644 --- a/command_test.go +++ b/command_test.go @@ -2343,3 +2343,90 @@ func TestSetContextPersistentPreRun(t *testing.T) { t.Error(err) } } + +const VersionFlag = "--version" +const HelpFlag = "--help" + +func TestNoRootRunCommandExecutedWithVersionSet(t *testing.T) { + rootCmd := &Command{Use: "root", Version: "1.0.0", Long: "Long description"} + rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun}) + + output, err := executeCommand(rootCmd) + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + checkStringContains(t, output, rootCmd.Long) + checkStringContains(t, output, HelpFlag) + checkStringContains(t, output, VersionFlag) +} + +func TestNoRootRunCommandExecutedWithoutVersionSet(t *testing.T) { + rootCmd := &Command{Use: "root", Long: "Long description"} + rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun}) + + output, err := executeCommand(rootCmd) + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + checkStringContains(t, output, rootCmd.Long) + checkStringContains(t, output, HelpFlag) + checkStringOmits(t, output, VersionFlag) +} + +func TestHelpCommandExecutedWithVersionSet(t *testing.T) { + rootCmd := &Command{Use: "root", Version: "1.0.0", Long: "Long description", Run: emptyRun} + rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun}) + + output, err := executeCommand(rootCmd, "help") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + checkStringContains(t, output, rootCmd.Long) + checkStringContains(t, output, HelpFlag) + checkStringContains(t, output, VersionFlag) +} + +func TestHelpCommandExecutedWithoutVersionSet(t *testing.T) { + rootCmd := &Command{Use: "root", Long: "Long description", Run: emptyRun} + rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun}) + + output, err := executeCommand(rootCmd, "help") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + checkStringContains(t, output, rootCmd.Long) + checkStringContains(t, output, HelpFlag) + checkStringOmits(t, output, VersionFlag) +} + +func TestHelpflagCommandExecutedWithVersionSet(t *testing.T) { + rootCmd := &Command{Use: "root", Version: "1.0.0", Long: "Long description", Run: emptyRun} + rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun}) + + output, err := executeCommand(rootCmd, HelpFlag) + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + checkStringContains(t, output, rootCmd.Long) + checkStringContains(t, output, HelpFlag) + checkStringContains(t, output, VersionFlag) +} + +func TestHelpflagCommandExecutedWithoutVersionSet(t *testing.T) { + rootCmd := &Command{Use: "root", Long: "Long description", Run: emptyRun} + rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun}) + + output, err := executeCommand(rootCmd, HelpFlag) + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + checkStringContains(t, output, rootCmd.Long) + checkStringContains(t, output, HelpFlag) + checkStringOmits(t, output, VersionFlag) +} From 3dc9761b36e8975006cd9b47d3b55b9751050a1e Mon Sep 17 00:00:00 2001 From: Dima Brusilovsky Date: Mon, 3 Oct 2022 17:52:01 +0300 Subject: [PATCH 42/74] Add allero to list of projects using cobra (#1819) --- projects_using_cobra.md | 1 + 1 file changed, 1 insertion(+) diff --git a/projects_using_cobra.md b/projects_using_cobra.md index b5b9dbf3..6865f88e 100644 --- a/projects_using_cobra.md +++ b/projects_using_cobra.md @@ -1,5 +1,6 @@ ## Projects using Cobra +- [Allero](https://github.com/allero-io/allero) - [Arduino CLI](https://github.com/arduino/arduino-cli) - [Bleve](https://blevesearch.com/) - [Cilium](https://cilium.io/) From 07034fee4995578a771c4185dab38cc16ac3f420 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 3 Oct 2022 08:52:25 -0600 Subject: [PATCH 43/74] build(deps): bump actions/stale from 5 to 6 (#1815) Bumps [actions/stale](https://github.com/actions/stale) from 5 to 6. - [Release notes](https://github.com/actions/stale/releases) - [Changelog](https://github.com/actions/stale/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/stale/compare/v5...v6) --- updated-dependencies: - dependency-name: actions/stale dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/stale.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index 8f8c7394..a558792b 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -10,7 +10,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/stale@v5 + - uses: actions/stale@v6 with: repo-token: ${{ secrets.GITHUB_TOKEN }} stale-issue-message: "The Cobra project currently lacks enough contributors to adequately respond to all issues. From 93d1913fb03362f97e95aeacc7d1541764cafc2f Mon Sep 17 00:00:00 2001 From: Yann Soubeyrand Date: Mon, 3 Oct 2022 16:52:50 +0200 Subject: [PATCH 44/74] Add OnFinalize method (#1788) This method is the OnInitialize counterpart. Like OnInitialize which allows loading the configuration before each command is executed, OnFinalize allows saving the configuration after each command has been executed. --- cobra.go | 7 +++++++ command.go | 8 ++++++++ 2 files changed, 15 insertions(+) diff --git a/cobra.go b/cobra.go index 1a95c3c1..fe44bc8a 100644 --- a/cobra.go +++ b/cobra.go @@ -40,6 +40,7 @@ var templateFuncs = template.FuncMap{ } var initializers []func() +var finalizers []func() const ( defaultPrefixMatching = false @@ -94,6 +95,12 @@ func OnInitialize(y ...func()) { initializers = append(initializers, y...) } +// OnFinalize sets the passed functions to be run when each command's +// Execute method is terminated. +func OnFinalize(y ...func()) { + finalizers = append(finalizers, y...) +} + // FIXME Gt is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra. // Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans, diff --git a/command.go b/command.go index 5ed3df8d..8ce5c3c8 100644 --- a/command.go +++ b/command.go @@ -834,6 +834,8 @@ func (c *Command) execute(a []string) (err error) { c.preRun() + defer c.postRun() + argWoFlags := c.Flags().Args() if c.DisableFlagParsing { argWoFlags = a @@ -904,6 +906,12 @@ func (c *Command) preRun() { } } +func (c *Command) postRun() { + for _, x := range finalizers { + x() + } +} + // ExecuteContext is the same as Execute(), but sets the ctx on the command. // Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs // functions. From 23fc5e099f7bb8b8f979e3928cb1078b9c939daa Mon Sep 17 00:00:00 2001 From: Varun Sharma Date: Mon, 3 Oct 2022 07:53:12 -0700 Subject: [PATCH 45/74] ci: add minimum GitHub token permissions for workflows (#1792) Signed-off-by: Varun Sharma --- .github/workflows/labeler.yml | 6 ++++++ .github/workflows/size-labeler.yml | 5 +++++ .github/workflows/stale.yml | 6 ++++++ .github/workflows/test.yml | 6 ++++++ 4 files changed, 23 insertions(+) diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml index e8b96514..17f451fd 100644 --- a/.github/workflows/labeler.yml +++ b/.github/workflows/labeler.yml @@ -2,8 +2,14 @@ name: "Pull Request Labeler" on: - pull_request_target +permissions: + contents: read + jobs: triage: + permissions: + contents: read # for actions/labeler to determine modified files + pull-requests: write # for actions/labeler to add labels to PRs runs-on: ubuntu-latest steps: - uses: actions/labeler@v4 diff --git a/.github/workflows/size-labeler.yml b/.github/workflows/size-labeler.yml index f04024fa..4c54d827 100644 --- a/.github/workflows/size-labeler.yml +++ b/.github/workflows/size-labeler.yml @@ -4,8 +4,13 @@ name: size-labeler on: [pull_request_target] +permissions: + contents: read + jobs: size-labeler: + permissions: + pull-requests: write # for codelytv/pr-size-labeler to add labels & comment on PRs runs-on: ubuntu-latest name: Label the PR size steps: diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index a558792b..2db5123d 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -4,9 +4,15 @@ on: schedule: - cron: "0 0 * * *" +permissions: + contents: read + jobs: stale: + permissions: + issues: write # for actions/stale to close stale issues + pull-requests: write # for actions/stale to close stale PRs runs-on: ubuntu-latest steps: diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 7865add6..a55d39fe 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -8,6 +8,9 @@ on: env: GO111MODULE: on +permissions: + contents: read + jobs: @@ -30,6 +33,9 @@ jobs: golangci-lint: + permissions: + contents: read # for actions/checkout to fetch code + pull-requests: read # for golangci/golangci-lint-action to fetch pull requests runs-on: ubuntu-latest steps: From d4040ad8dbc351b7eb88b2ffcff6f3642bce8ce1 Mon Sep 17 00:00:00 2001 From: Marc Khouzam Date: Mon, 3 Oct 2022 13:06:04 -0400 Subject: [PATCH 46/74] Allow user to add completion for powershell alias (#1621) When a user has an alias in powershell, she will need to register that alias for completion. To make that possible, we store the completion logic into a scriptblock variable which can easily be accessed by the user to register aliases. For example, if the user defines an alias for `helm`: PS> sal h helm she will need to register the alias like so: PS> Register-ArgumentCompleter -CommandName 'h' -ScriptBlock $__helmCompleterBlock Signed-off-by: Marc Khouzam --- powershell_completions.go | 26 +++++++++++++++++--------- shell_completions.md | 15 +++++++++++++++ 2 files changed, 32 insertions(+), 9 deletions(-) diff --git a/powershell_completions.go b/powershell_completions.go index 351ded65..004de42e 100644 --- a/powershell_completions.go +++ b/powershell_completions.go @@ -22,9 +22,15 @@ import ( "fmt" "io" "os" + "strings" ) func genPowerShellComp(buf io.StringWriter, name string, includeDesc bool) { + // Variables should not contain a '-' or ':' character + nameForVar := name + nameForVar = strings.Replace(nameForVar, "-", "_", -1) + nameForVar = strings.Replace(nameForVar, ":", "_", -1) + compCmd := ShellCompRequestCmd if !includeDesc { compCmd = ShellCompNoDescRequestCmd @@ -41,7 +47,7 @@ filter __%[1]s_escapeStringWithSpecialChars { `+" $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|\"|`|\\||<|>|&','`$&'"+` } -Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock { +[scriptblock]$__%[2]sCompleterBlock = { param( $WordToComplete, $CommandAst, @@ -66,17 +72,17 @@ Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock { } __%[1]s_debug "Truncated command: $Command" - $ShellCompDirectiveError=%[3]d - $ShellCompDirectiveNoSpace=%[4]d - $ShellCompDirectiveNoFileComp=%[5]d - $ShellCompDirectiveFilterFileExt=%[6]d - $ShellCompDirectiveFilterDirs=%[7]d + $ShellCompDirectiveError=%[4]d + $ShellCompDirectiveNoSpace=%[5]d + $ShellCompDirectiveNoFileComp=%[6]d + $ShellCompDirectiveFilterFileExt=%[7]d + $ShellCompDirectiveFilterDirs=%[8]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" + $RequestComp="$Program %[3]s $Arguments" __%[1]s_debug "RequestComp: $RequestComp" # we cannot use $WordToComplete because it @@ -106,7 +112,7 @@ Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock { __%[1]s_debug "Calling $RequestComp" # First disable ActiveHelp which is not supported for Powershell - $env:%[8]s=0 + $env:%[9]s=0 #call the command store the output in $out and redirect stderr and stdout to null # $Out is an array contains each line per element @@ -257,7 +263,9 @@ Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock { } } -`, name, compCmd, + +Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock $__%[2]sCompleterBlock +`, name, nameForVar, compCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name))) } diff --git a/shell_completions.md b/shell_completions.md index a0957b4d..553ee5df 100644 --- a/shell_completions.md +++ b/shell_completions.md @@ -535,6 +535,21 @@ search for a keyword in charts $ helm s[tab] search show status ``` +### Aliases + +You can also configure `powershell` aliases for your program and they will also support completions. + +``` +$ sal aliasname origcommand +$ Register-ArgumentCompleter -CommandName 'aliasname' -ScriptBlock $__origcommandCompleterBlock + +# and now when you run `aliasname` completion will make +# suggestions as it did for `origcommand`. + +$ aliasname +completion firstcommand secondcommand +``` +The name of the completer block variable is of the form `$__CompleterBlock` where every `-` and `:` in the program name have been replaced with `_`, to respect powershell naming syntax. ### Limitations From 212ea4078323771dc49b6f25a41d84efbaac3a4c Mon Sep 17 00:00:00 2001 From: Marc Khouzam Date: Tue, 4 Oct 2022 18:41:30 -0400 Subject: [PATCH 47/74] Include --help and --version flag in completion (#1813) Fixes #1786 The --help, -h, --version and -v flags are normally added when the `execute()` function is called on a command. When doing completion we don't call `execute()` so we need to add these flags explicitly to the command being completed. Also, we disable all further completions if the 'help' or 'version' flags are present on the command-line. Signed-off-by: Marc Khouzam --- command.go | 4 + completions.go | 24 +++++ completions_test.go | 234 +++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 257 insertions(+), 5 deletions(-) diff --git a/command.go b/command.go index 8ce5c3c8..64f1d5f4 100644 --- a/command.go +++ b/command.go @@ -30,6 +30,8 @@ import ( flag "github.com/spf13/pflag" ) +const FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra" + // FParseErrWhitelist configures Flag parse errors to be ignored type FParseErrWhitelist flag.ParseErrorsWhitelist @@ -1064,6 +1066,7 @@ func (c *Command) InitDefaultHelpFlag() { usage += c.Name() } c.Flags().BoolP("help", "h", false, usage) + _ = c.Flags().SetAnnotation("help", FlagSetByCobraAnnotation, []string{"true"}) } } @@ -1089,6 +1092,7 @@ func (c *Command) InitDefaultVersionFlag() { } else { c.Flags().Bool("version", false, usage) } + _ = c.Flags().SetAnnotation("version", FlagSetByCobraAnnotation, []string{"true"}) } } diff --git a/completions.go b/completions.go index f8bf4f69..d8fa1f77 100644 --- a/completions.go +++ b/completions.go @@ -274,6 +274,12 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi } finalCmd.ctx = c.ctx + // These flags are normally added when `execute()` is called on `finalCmd`, + // however, when doing completion, we don't call `finalCmd.execute()`. + // Let's add the --help and --version flag ourselves. + finalCmd.InitDefaultHelpFlag() + finalCmd.InitDefaultVersionFlag() + // Check if we are doing flag value completion before parsing the flags. // This is important because if we are completing a flag value, we need to also // remove the flag name argument from the list of finalArgs or else the parsing @@ -306,6 +312,12 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi } } + // Look for the --help or --version flags. If they are present, + // there should be no further completions. + if helpOrVersionFlagPresent(finalCmd) { + return finalCmd, []string{}, ShellCompDirectiveNoFileComp, nil + } + // We only remove the flags from the arguments if DisableFlagParsing is not set. // This is important for commands which have requested to do their own flag completion. if !finalCmd.DisableFlagParsing { @@ -477,6 +489,18 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi return finalCmd, completions, directive, nil } +func helpOrVersionFlagPresent(cmd *Command) bool { + if versionFlag := cmd.Flags().Lookup("version"); versionFlag != nil && + len(versionFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && versionFlag.Changed { + return true + } + if helpFlag := cmd.Flags().Lookup("help"); helpFlag != nil && + len(helpFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && helpFlag.Changed { + return true + } + return false +} + func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string { if nonCompletableFlag(flag) { return []string{} diff --git a/completions_test.go b/completions_test.go index c5f11fa5..abac12e4 100644 --- a/completions_test.go +++ b/completions_test.go @@ -493,8 +493,9 @@ func TestFlagNameCompletionInGo(t *testing.T) { Run: emptyRun, } childCmd := &Command{ - Use: "childCmd", - Run: emptyRun, + Use: "childCmd", + Version: "1.2.3", + Run: emptyRun, } rootCmd.AddCommand(childCmd) @@ -528,6 +529,8 @@ func TestFlagNameCompletionInGo(t *testing.T) { expected = strings.Join([]string{ "--first", "-f", + "--help", + "-h", "--second", "-s", ":4", @@ -561,7 +564,11 @@ func TestFlagNameCompletionInGo(t *testing.T) { expected = strings.Join([]string{ "--second", "-s", + "--help", + "-h", "--subFlag", + "--version", + "-v", ":4", "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n") @@ -576,9 +583,10 @@ func TestFlagNameCompletionInGoWithDesc(t *testing.T) { Run: emptyRun, } childCmd := &Command{ - Use: "childCmd", - Short: "first command", - Run: emptyRun, + Use: "childCmd", + Short: "first command", + Version: "1.2.3", + Run: emptyRun, } rootCmd.AddCommand(childCmd) @@ -612,6 +620,8 @@ func TestFlagNameCompletionInGoWithDesc(t *testing.T) { expected = strings.Join([]string{ "--first\tfirst flag", "-f\tfirst flag", + "--help\thelp for root", + "-h\thelp for root", "--second\tsecond flag", "-s\tsecond flag", ":4", @@ -645,7 +655,11 @@ func TestFlagNameCompletionInGoWithDesc(t *testing.T) { expected = strings.Join([]string{ "--second\tsecond flag", "-s\tsecond flag", + "--help\thelp for childCmd", + "-h\thelp for childCmd", "--subFlag\tsub flag", + "--version\tversion for childCmd", + "-v\tversion for childCmd", ":4", "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n") @@ -688,6 +702,7 @@ func TestFlagNameCompletionRepeat(t *testing.T) { expected := strings.Join([]string{ "--array", "--bslice", + "--help", "--second", "--slice", ":4", @@ -709,6 +724,7 @@ func TestFlagNameCompletionRepeat(t *testing.T) { expected = strings.Join([]string{ "--array", "--bslice", + "--help", "--slice", ":4", "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n") @@ -731,6 +747,7 @@ func TestFlagNameCompletionRepeat(t *testing.T) { "--array", "--bslice", "--first", + "--help", "--second", "--slice", ":4", @@ -756,6 +773,8 @@ func TestFlagNameCompletionRepeat(t *testing.T) { "-b", "--first", "-f", + "--help", + "-h", "--second", "-s", "--slice", @@ -1792,6 +1811,7 @@ func TestFlagCompletionWithNotInterspersedArgs(t *testing.T) { expected := strings.Join([]string{ "--bool\ttest bool flag", + "--help\thelp for child", "--string\ttest string flag", ":4", "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n") @@ -2602,6 +2622,8 @@ func TestCompleteWithDisableFlagParsing(t *testing.T) { expected := strings.Join([]string{ "--persistent", "-p", + "--help", + "-h", "--nonPersistent", "-n", "--flag", @@ -2624,6 +2646,8 @@ func TestCompleteWithDisableFlagParsing(t *testing.T) { expected = strings.Join([]string{ "--persistent", "-p", + "--help", + "-h", "--nonPersistent", "-n", ":4", @@ -2753,6 +2777,8 @@ func TestCompletionForGroupedFlags(t *testing.T) { expectedOutput: strings.Join([]string{ "--ingroup1", "--ingroup2", + "--help", + "-h", "--ingroup3", "--nogroup", ":4", @@ -2851,6 +2877,8 @@ func TestCompletionForMutuallyExclusiveFlags(t *testing.T) { expectedOutput: strings.Join([]string{ "--ingroup1", "--ingroup2", + "--help", + "-h", "--ingroup3", "--nogroup", ":4", @@ -2861,6 +2889,8 @@ func TestCompletionForMutuallyExclusiveFlags(t *testing.T) { args: []string{"child", "--ingroup1", "8", "-"}, expectedOutput: strings.Join([]string{ "--ingroup1", // Should be suggested again since it is a slice + "--help", + "-h", "--nogroup", ":4", "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"), @@ -2869,6 +2899,8 @@ func TestCompletionForMutuallyExclusiveFlags(t *testing.T) { desc: "group ignored if some flags not applicable", args: []string{"--ingroup1", "8", "-"}, expectedOutput: strings.Join([]string{ + "--help", + "-h", "--ingroup1", "--ingroup2", ":4", @@ -2891,3 +2923,195 @@ func TestCompletionForMutuallyExclusiveFlags(t *testing.T) { }) } } + +func TestCompletionCobraFlags(t *testing.T) { + getCmd := func() *Command { + rootCmd := &Command{ + Use: "root", + Version: "1.1.1", + Run: emptyRun, + } + childCmd := &Command{ + Use: "child", + Version: "1.1.1", + Run: emptyRun, + ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { + return []string{"extra"}, ShellCompDirectiveNoFileComp + }, + } + childCmd2 := &Command{ + Use: "child2", + Version: "1.1.1", + Run: emptyRun, + ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { + return []string{"extra2"}, ShellCompDirectiveNoFileComp + }, + } + childCmd3 := &Command{ + Use: "child3", + Version: "1.1.1", + Run: emptyRun, + ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { + return []string{"extra3"}, ShellCompDirectiveNoFileComp + }, + } + + rootCmd.AddCommand(childCmd, childCmd2, childCmd3) + + _ = childCmd.Flags().Bool("bool", false, "A bool flag") + _ = childCmd.MarkFlagRequired("bool") + + // Have a command that adds its own help and version flag + _ = childCmd2.Flags().BoolP("help", "h", false, "My own help") + _ = childCmd2.Flags().BoolP("version", "v", false, "My own version") + + // Have a command that only adds its own -v flag + _ = childCmd3.Flags().BoolP("verbose", "v", false, "Not a version flag") + + return rootCmd + } + + // Each test case uses a unique command from the function above. + testcases := []struct { + desc string + args []string + expectedOutput string + }{ + { + desc: "completion of help and version flags", + args: []string{"-"}, + expectedOutput: strings.Join([]string{ + "--help", + "-h", + "--version", + "-v", + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"), + }, + { + desc: "no completion after --help flag", + args: []string{"--help", ""}, + expectedOutput: strings.Join([]string{ + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"), + }, + { + desc: "no completion after -h flag", + args: []string{"-h", ""}, + expectedOutput: strings.Join([]string{ + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"), + }, + { + desc: "no completion after --version flag", + args: []string{"--version", ""}, + expectedOutput: strings.Join([]string{ + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"), + }, + { + desc: "no completion after -v flag", + args: []string{"-v", ""}, + expectedOutput: strings.Join([]string{ + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"), + }, + { + desc: "no completion after --help flag even with other completions", + args: []string{"child", "--help", ""}, + expectedOutput: strings.Join([]string{ + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"), + }, + { + desc: "no completion after -h flag even with other completions", + args: []string{"child", "-h", ""}, + expectedOutput: strings.Join([]string{ + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"), + }, + { + desc: "no completion after --version flag even with other completions", + args: []string{"child", "--version", ""}, + expectedOutput: strings.Join([]string{ + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"), + }, + { + desc: "no completion after -v flag even with other completions", + args: []string{"child", "-v", ""}, + expectedOutput: strings.Join([]string{ + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"), + }, + { + desc: "no completion after -v flag even with other flag completions", + args: []string{"child", "-v", "-"}, + expectedOutput: strings.Join([]string{ + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"), + }, + { + desc: "completion after --help flag when created by program", + args: []string{"child2", "--help", ""}, + expectedOutput: strings.Join([]string{ + "extra2", + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"), + }, + { + desc: "completion after -h flag when created by program", + args: []string{"child2", "-h", ""}, + expectedOutput: strings.Join([]string{ + "extra2", + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"), + }, + { + desc: "completion after --version flag when created by program", + args: []string{"child2", "--version", ""}, + expectedOutput: strings.Join([]string{ + "extra2", + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"), + }, + { + desc: "completion after -v flag when created by program", + args: []string{"child2", "-v", ""}, + expectedOutput: strings.Join([]string{ + "extra2", + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"), + }, + { + desc: "completion after --version when only -v flag was created by program", + args: []string{"child3", "--version", ""}, + expectedOutput: strings.Join([]string{ + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"), + }, + { + desc: "completion after -v flag when only -v flag was created by program", + args: []string{"child3", "-v", ""}, + expectedOutput: strings.Join([]string{ + "extra3", + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"), + }, + } + + for _, tc := range testcases { + t.Run(tc.desc, func(t *testing.T) { + c := getCmd() + args := []string{ShellCompNoDescRequestCmd} + args = append(args, tc.args...) + output, err := executeCommand(c, args...) + switch { + case err == nil && output != tc.expectedOutput: + t.Errorf("expected: %q, got: %q", tc.expectedOutput, output) + case err != nil: + t.Errorf("Unexpected error %q", err) + } + }) + } +} From 2169adb5749372c64cdd303864ae8a444da6350f Mon Sep 17 00:00:00 2001 From: aawsome <37850842+aawsome@users.noreply.github.com> Date: Mon, 10 Oct 2022 22:59:11 +0200 Subject: [PATCH 48/74] Add groups for commands in help (#1003) * Add tests for grouping commands * Adds Additional Command section in help Signed-off-by: Marc Khouzam Co-authored-by: Marc Khouzam --- README.md | 1 + command.go | 80 +++++++++++++++++++++++++++++++++++++++-- command_test.go | 95 +++++++++++++++++++++++++++++++++++++++++++++++++ completions.go | 1 + user_guide.md | 7 ++++ 5 files changed, 181 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 08e4fa52..7cc726be 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ Cobra provides: * Global, local and cascading flags * Intelligent suggestions (`app srver`... did you mean `app server`?) * Automatic help generation for commands and flags +* Grouping help for subcommands * Automatic help flag recognition of `-h`, `--help`, etc. * Automatically generated shell autocomplete for your application (bash, zsh, fish, powershell) * Automatically generated man pages for your application diff --git a/command.go b/command.go index 64f1d5f4..ad265073 100644 --- a/command.go +++ b/command.go @@ -35,6 +35,12 @@ const FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra" // FParseErrWhitelist configures Flag parse errors to be ignored type FParseErrWhitelist flag.ParseErrorsWhitelist +// Structure to manage groups for commands +type Group struct { + ID string + Title string +} + // Command is just that, a command for your application. // E.g. 'go run ...' - 'run' is the command. Cobra requires // you to define the usage and description as part of your command @@ -61,6 +67,9 @@ type Command struct { // Short is the short description shown in the 'help' output. Short string + // The group id under which this subcommand is grouped in the 'help' output of its parent. + GroupID string + // Long is the long message shown in the 'help ' output. Long string @@ -128,6 +137,9 @@ type Command struct { // PersistentPostRunE: PersistentPostRun but returns an error. PersistentPostRunE func(cmd *Command, args []string) error + // groups for subcommands + commandgroups []*Group + // args is actual args parsed from flags. args []string // flagErrorBuf contains all error messages from pflag. @@ -160,6 +172,12 @@ type Command struct { // helpCommand is command with usage 'help'. If it's not defined by user, // cobra uses default help command. helpCommand *Command + // helpCommandGroupID is the group id for the helpCommand + helpCommandGroupID string + + // completionCommandGroupID is the group id for the completion command + completionCommandGroupID string + // versionTemplate is the version template defined by user. versionTemplate string @@ -303,6 +321,21 @@ func (c *Command) SetHelpCommand(cmd *Command) { c.helpCommand = cmd } +// SetHelpCommandGroup sets the group id of the help command. +func (c *Command) SetHelpCommandGroupID(groupID string) { + if c.helpCommand != nil { + c.helpCommand.GroupID = groupID + } + // helpCommandGroupID is used if no helpCommand is defined by the user + c.helpCommandGroupID = groupID +} + +// SetCompletionCommandGroup sets the group id of the completion command. +func (c *Command) SetCompletionCommandGroupID(groupID string) { + // completionCommandGroupID is used if no completion command is defined by the user + c.Root().completionCommandGroupID = groupID +} + // SetHelpTemplate sets help template to be used. Application can use it to set custom template. func (c *Command) SetHelpTemplate(s string) { c.helpTemplate = s @@ -511,10 +544,16 @@ Aliases: {{.NameAndAliases}}{{end}}{{if .HasExample}} Examples: -{{.Example}}{{end}}{{if .HasAvailableSubCommands}} +{{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{$cmds := .Commands}}{{if eq (len .Groups) 0}} -Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}} - {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}} +Available Commands:{{range $cmds}}{{if (or .IsAvailableCommand (eq .Name "help"))}} + {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{else}}{{range $group := .Groups}} + +{{.Title}}{{range $cmds}}{{if (and (eq .GroupID $group.ID) (or .IsAvailableCommand (eq .Name "help")))}} + {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if not .AllChildCommandsHaveGroup}} + +Additional Commands:{{range $cmds}}{{if (and (eq .GroupID "") (or .IsAvailableCommand (eq .Name "help")))}} + {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}} Flags: {{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}} @@ -1140,6 +1179,7 @@ Simply type ` + c.Name() + ` help [path to command] for full details.`, CheckErr(cmd.Help()) } }, + GroupID: c.helpCommandGroupID, } } c.RemoveCommand(c.helpCommand) @@ -1178,6 +1218,10 @@ func (c *Command) AddCommand(cmds ...*Command) { panic("Command can't be a child of itself") } cmds[i].parent = c + // if Group is not defined let the developer know right away + if x.GroupID != "" && !c.ContainsGroup(x.GroupID) { + panic(fmt.Sprintf("Group id '%s' is not defined for subcommand '%s'", x.GroupID, cmds[i].CommandPath())) + } // update max lengths usageLen := len(x.Use) if usageLen > c.commandsMaxUseLen { @@ -1200,6 +1244,36 @@ func (c *Command) AddCommand(cmds ...*Command) { } } +// Groups returns a slice of child command groups. +func (c *Command) Groups() []*Group { + return c.commandgroups +} + +// AllChildCommandsHaveGroup returns if all subcommands are assigned to a group +func (c *Command) AllChildCommandsHaveGroup() bool { + for _, sub := range c.commands { + if (sub.IsAvailableCommand() || sub == c.helpCommand) && sub.GroupID == "" { + return false + } + } + return true +} + +// ContainGroups return if groupID exists in the list of command groups. +func (c *Command) ContainsGroup(groupID string) bool { + for _, x := range c.commandgroups { + if x.ID == groupID { + return true + } + } + return false +} + +// AddGroup adds one or more command groups to this parent command. +func (c *Command) AddGroup(groups ...*Group) { + c.commandgroups = append(c.commandgroups, groups...) +} + // RemoveCommand removes one or more commands from a parent command. func (c *Command) RemoveCommand(cmds ...*Command) { commands := []*Command{} diff --git a/command_test.go b/command_test.go index b3dd0304..0adec93d 100644 --- a/command_test.go +++ b/command_test.go @@ -1767,6 +1767,101 @@ func TestEnableCommandSortingIsDisabled(t *testing.T) { EnableCommandSorting = defaultCommandSorting } +func TestUsageWithGroup(t *testing.T) { + var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun} + rootCmd.CompletionOptions.DisableDefaultCmd = true + + rootCmd.AddGroup(&Group{ID: "group1", Title: "group1"}) + rootCmd.AddGroup(&Group{ID: "group2", Title: "group2"}) + + rootCmd.AddCommand(&Command{Use: "cmd1", GroupID: "group1", Run: emptyRun}) + rootCmd.AddCommand(&Command{Use: "cmd2", GroupID: "group2", Run: emptyRun}) + + output, err := executeCommand(rootCmd, "--help") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + // help should be ungrouped here + checkStringContains(t, output, "\nAdditional Commands:\n help") + checkStringContains(t, output, "\ngroup1\n cmd1") + checkStringContains(t, output, "\ngroup2\n cmd2") +} + +func TestUsageHelpGroup(t *testing.T) { + var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun} + rootCmd.CompletionOptions.DisableDefaultCmd = true + + rootCmd.AddGroup(&Group{ID: "group", Title: "group"}) + rootCmd.AddCommand(&Command{Use: "xxx", GroupID: "group", Run: emptyRun}) + rootCmd.SetHelpCommandGroupID("group") + + output, err := executeCommand(rootCmd, "--help") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + // now help should be grouped under "group" + checkStringOmits(t, output, "\nAdditional Commands:\n help") + checkStringContains(t, output, "\ngroup\n help") +} + +func TestUsageCompletionGroup(t *testing.T) { + var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun} + + rootCmd.AddGroup(&Group{ID: "group", Title: "group"}) + rootCmd.AddGroup(&Group{ID: "help", Title: "help"}) + + rootCmd.AddCommand(&Command{Use: "xxx", GroupID: "group", Run: emptyRun}) + rootCmd.SetHelpCommandGroupID("help") + rootCmd.SetCompletionCommandGroupID("group") + + output, err := executeCommand(rootCmd, "--help") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + // now completion should be grouped under "group" + checkStringOmits(t, output, "\nAdditional Commands:\n completion") + checkStringContains(t, output, "\ngroup\n completion") +} + +func TestUngroupedCommand(t *testing.T) { + var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun} + + rootCmd.AddGroup(&Group{ID: "group", Title: "group"}) + rootCmd.AddGroup(&Group{ID: "help", Title: "help"}) + + rootCmd.AddCommand(&Command{Use: "xxx", GroupID: "group", Run: emptyRun}) + rootCmd.SetHelpCommandGroupID("help") + rootCmd.SetCompletionCommandGroupID("group") + + // Add a command without a group + rootCmd.AddCommand(&Command{Use: "yyy", Run: emptyRun}) + + output, err := executeCommand(rootCmd, "--help") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + // The yyy command should be in the additional command "group" + checkStringContains(t, output, "\nAdditional Commands:\n yyy") +} + +func TestAddGroup(t *testing.T) { + var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun} + + rootCmd.AddGroup(&Group{ID: "group", Title: "Test group"}) + rootCmd.AddCommand(&Command{Use: "cmd", GroupID: "group", Run: emptyRun}) + + output, err := executeCommand(rootCmd, "--help") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + checkStringContains(t, output, "\nTest group\n cmd") +} + func TestSetOutput(t *testing.T) { c := &Command{} c.SetOutput(nil) diff --git a/completions.go b/completions.go index d8fa1f77..122d7529 100644 --- a/completions.go +++ b/completions.go @@ -673,6 +673,7 @@ See each sub-command's help for details on how to use the generated script. Args: NoArgs, ValidArgsFunction: NoFileCompletions, Hidden: c.CompletionOptions.HiddenDefaultCmd, + GroupID: c.completionCommandGroupID, } c.AddCommand(completionCmd) diff --git a/user_guide.md b/user_guide.md index c694d871..977306aa 100644 --- a/user_guide.md +++ b/user_guide.md @@ -490,6 +490,13 @@ command and flag definitions are needed. Help is just a command like any other. There is no special logic or behavior around it. In fact, you can provide your own if you want. +### Grouping commands in help + +Cobra supports grouping of available commands. Groups must be explicitly defined by `AddGroup` and set by +the `GroupId` element of a subcommand. The groups will appear in the same order as they are defined. +If you use the generated `help` or `completion` commands, you can set the group ids by `SetHelpCommandGroupId` +and `SetCompletionCommandGroupId`, respectively. + ### Defining your own help You can provide your own Help command or your own template for the default command to use From 860791844ed3a2e544a9b9bbbcb14144a948ad20 Mon Sep 17 00:00:00 2001 From: Gustavo Bazan Date: Tue, 11 Oct 2022 00:06:30 +0100 Subject: [PATCH 49/74] feat: make InitDefaultCompletionCmd public (#1467) * feat: make InitDefaultCompletionCmd public * PR comments * Update man_docs_test.go * Update README.md --- command.go | 2 +- completions.go | 4 ++-- doc/README.md | 5 +++++ 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/command.go b/command.go index ad265073..9d5e9cf5 100644 --- a/command.go +++ b/command.go @@ -996,7 +996,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) { // initialize help at the last point to allow for user overriding c.InitDefaultHelpCmd() // initialize completion at the last point to allow for user overriding - c.initDefaultCompletionCmd() + c.InitDefaultCompletionCmd() args := c.args diff --git a/completions.go b/completions.go index 122d7529..e8a0206d 100644 --- a/completions.go +++ b/completions.go @@ -645,12 +645,12 @@ func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*p return flag, trimmedArgs, lastArg, nil } -// initDefaultCompletionCmd adds a default 'completion' command to c. +// InitDefaultCompletionCmd adds a default 'completion' command to c. // This function will do nothing if any of the following is true: // 1- the feature has been explicitly disabled by the program, // 2- c has no subcommands (to avoid creating one), // 3- c already has a 'completion' command provided by the program. -func (c *Command) initDefaultCompletionCmd() { +func (c *Command) InitDefaultCompletionCmd() { if c.CompletionOptions.DisableDefaultCmd || !c.HasSubCommands() { return } diff --git a/doc/README.md b/doc/README.md index 6ea4eb66..8e07baae 100644 --- a/doc/README.md +++ b/doc/README.md @@ -7,6 +7,11 @@ ## Options ### `DisableAutoGenTag` + You may set `cmd.DisableAutoGenTag = true` to _entirely_ remove the auto generated string "Auto generated by spf13/cobra..." from any documentation source. + +### `InitDefaultCompletionCmd` + +You may call `cmd.InitDefaultCompletionCmd()` to document the default autocompletion command. From 1424b7b92743e634e20f611e99a495e411fa4732 Mon Sep 17 00:00:00 2001 From: Fabian Kammel Date: Thu, 13 Oct 2022 15:47:58 +0200 Subject: [PATCH 50/74] Add Constellation to projects using cobra. (#1829) --- projects_using_cobra.md | 1 + 1 file changed, 1 insertion(+) diff --git a/projects_using_cobra.md b/projects_using_cobra.md index 6865f88e..99fbd0b8 100644 --- a/projects_using_cobra.md +++ b/projects_using_cobra.md @@ -6,6 +6,7 @@ - [Cilium](https://cilium.io/) - [CloudQuery](https://github.com/cloudquery/cloudquery) - [CockroachDB](https://www.cockroachlabs.com/) +- [Constellation](https://github.com/edgelesssys/constellation) - [Cosmos SDK](https://github.com/cosmos/cosmos-sdk) - [Datree](https://github.com/datreeio/datree) - [Delve](https://github.com/derekparker/delve) From badcce14f8e828cda4d8ac404a12448700de1441 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Mon, 17 Oct 2022 22:24:27 +0300 Subject: [PATCH 51/74] style(bash-v2): various cleanups (#1702) * use arithmetic evaluation in numeric context * remove unnecessary $ from array index variables * [[ ]] over [ ], == over =, remove unnecessary quoting * use ${foo-} rather than ${foo:-} in emptiness check The result of the expansion is null no matter if the variable is unset or null in both cases; the former form is arguably easier on the eye. * remove unnecessary trailing linefeed removal No longer needed as of f464d6c82e9af74b7a46301a775163984af32cd1, saves a subshell. * use herestring in activehelp extraction Herestrings read cleaner than process substitutions, and work in posix mode (but we do and will have some process substitutions so this doesn't matter much). Both approaches may end up using temporary files. --- bash_completionsV2.go | 51 +++++++++++++++++++++---------------------- 1 file changed, 25 insertions(+), 26 deletions(-) diff --git a/bash_completionsV2.go b/bash_completionsV2.go index bb4b7189..78f43b91 100644 --- a/bash_completionsV2.go +++ b/bash_completionsV2.go @@ -38,7 +38,7 @@ func genBashComp(buf io.StringWriter, name string, includeDesc bool) { __%[1]s_debug() { - if [[ -n ${BASH_COMP_DEBUG_FILE:-} ]]; then + if [[ -n ${BASH_COMP_DEBUG_FILE-} ]]; then echo "$*" >> "${BASH_COMP_DEBUG_FILE}" fi } @@ -65,7 +65,7 @@ __%[1]s_get_completion_results() { lastChar=${lastParam:$((${#lastParam}-1)):1} __%[1]s_debug "lastParam ${lastParam}, lastChar ${lastChar}" - if [ -z "${cur}" ] && [ "${lastChar}" != "=" ]; then + if [[ -z ${cur} && ${lastChar} != = ]]; then # 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" @@ -75,7 +75,7 @@ __%[1]s_get_completion_results() { # When completing a flag with an = (e.g., %[1]s -n=) # bash focuses on the part after the =, so we need to remove # the flag part from $cur - if [[ "${cur}" == -*=* ]]; then + if [[ ${cur} == -*=* ]]; then cur="${cur#*=}" fi @@ -87,7 +87,7 @@ __%[1]s_get_completion_results() { directive=${out##*:} # Remove the directive out=${out%%:*} - if [ "${directive}" = "${out}" ]; then + if [[ ${directive} == "${out}" ]]; then # There is not directive specified directive=0 fi @@ -102,21 +102,21 @@ __%[1]s_process_completion_results() { local shellCompDirectiveFilterFileExt=%[6]d local shellCompDirectiveFilterDirs=%[7]d - if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then + if (((directive & shellCompDirectiveError) != 0)); then # Error code. No completion. __%[1]s_debug "Received error from custom completion go code" return else - if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then - if [[ $(type -t compopt) = "builtin" ]]; then + if (((directive & shellCompDirectiveNoSpace) != 0)); then + if [[ $(type -t compopt) == builtin ]]; then __%[1]s_debug "Activating no space" compopt -o nospace else __%[1]s_debug "No space directive not supported in this version of bash" fi fi - if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then - if [[ $(type -t compopt) = "builtin" ]]; then + if (((directive & shellCompDirectiveNoFileComp) != 0)); then + if [[ $(type -t compopt) == builtin ]]; then __%[1]s_debug "Activating no file completion" compopt +o default else @@ -130,7 +130,7 @@ __%[1]s_process_completion_results() { local activeHelp=() __%[1]s_extract_activeHelp - if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then + if (((directive & shellCompDirectiveFilterFileExt) != 0)); then # File extension filtering local fullFilter filter filteringCmd @@ -143,13 +143,12 @@ __%[1]s_process_completion_results() { filteringCmd="_filedir $fullFilter" __%[1]s_debug "File filtering command: $filteringCmd" $filteringCmd - elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then + elif (((directive & shellCompDirectiveFilterDirs) != 0)); then # File completion for directories only - # Use printf to strip any trailing newline local subdir - subdir=$(printf "%%s" "${completions[0]}") - if [ -n "$subdir" ]; then + subdir=${completions[0]} + if [[ -n $subdir ]]; then __%[1]s_debug "Listing directories in $subdir" pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return else @@ -164,7 +163,7 @@ __%[1]s_process_completion_results() { __%[1]s_handle_special_char "$cur" = # Print the activeHelp statements before we finish - if [ ${#activeHelp[*]} -ne 0 ]; then + if ((${#activeHelp[*]} != 0)); then printf "\n"; printf "%%s\n" "${activeHelp[@]}" printf "\n" @@ -188,17 +187,17 @@ __%[1]s_extract_activeHelp() { local endIndex=${#activeHelpMarker} while IFS='' read -r comp; do - if [ "${comp:0:endIndex}" = "$activeHelpMarker" ]; then + if [[ ${comp:0:endIndex} == $activeHelpMarker ]]; then comp=${comp:endIndex} __%[1]s_debug "ActiveHelp found: $comp" - if [ -n "$comp" ]; then + if [[ -n $comp ]]; then activeHelp+=("$comp") fi else # Not an activeHelp line but a normal completion completions+=("$comp") fi - done < <(printf "%%s\n" "${out}") + done <<<"${out}" } __%[1]s_handle_completion_types() { @@ -254,7 +253,7 @@ __%[1]s_handle_standard_completion_case() { done < <(printf "%%s\n" "${completions[@]}") # If there is a single completion left, remove the description text - if [ ${#COMPREPLY[*]} -eq 1 ]; then + if ((${#COMPREPLY[*]} == 1)); then __%[1]s_debug "COMPREPLY[0]: ${COMPREPLY[0]}" comp="${COMPREPLY[0]%%%%$tab*}" __%[1]s_debug "Removed description from single completion, which is now: ${comp}" @@ -271,8 +270,8 @@ __%[1]s_handle_special_char() if [[ "$comp" == *${char}* && "$COMP_WORDBREAKS" == *${char}* ]]; then local word=${comp%%"${comp##*${char}}"} local idx=${#COMPREPLY[*]} - while [[ $((--idx)) -ge 0 ]]; do - COMPREPLY[$idx]=${COMPREPLY[$idx]#"$word"} + while ((--idx >= 0)); do + COMPREPLY[idx]=${COMPREPLY[idx]#"$word"} done fi } @@ -298,7 +297,7 @@ __%[1]s_format_comp_descriptions() # Make sure we can fit a description of at least 8 characters # if we are to align the descriptions. - if [[ $maxdesclength -gt 8 ]]; then + if ((maxdesclength > 8)); then # Add the proper number of spaces to align the descriptions for ((i = ${#comp} ; i < longest ; i++)); do comp+=" " @@ -310,8 +309,8 @@ __%[1]s_format_comp_descriptions() # If there is enough space for any description text, # truncate the descriptions that are too long for the shell width - if [ $maxdesclength -gt 0 ]; then - if [ ${#desc} -gt $maxdesclength ]; then + if ((maxdesclength > 0)); then + if ((${#desc} > maxdesclength)); then desc=${desc:0:$(( maxdesclength - 1 ))} desc+="…" fi @@ -332,9 +331,9 @@ __start_%[1]s() # Call _init_completion from the bash-completion package # to prepare the arguments properly if declare -F _init_completion >/dev/null 2>&1; then - _init_completion -n "=:" || return + _init_completion -n =: || return else - __%[1]s_init_completion -n "=:" || return + __%[1]s_init_completion -n =: || return fi __%[1]s_debug From 4b9d00dfecd605048ddf3ad2a81afcab381ac1ae Mon Sep 17 00:00:00 2001 From: doniacld Date: Thu, 20 Oct 2022 22:33:37 +0200 Subject: [PATCH 52/74] Replace deprecated ExactValidArgs with MatchAll in user_guide and shell_completions example (#1836) --- shell_completions.md | 2 +- user_guide.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/shell_completions.md b/shell_completions.md index 553ee5df..286c2525 100644 --- a/shell_completions.md +++ b/shell_completions.md @@ -71,7 +71,7 @@ PowerShell: `,cmd.Root().Name()), DisableFlagsInUseLine: true, ValidArgs: []string{"bash", "zsh", "fish", "powershell"}, - Args: cobra.ExactValidArgs(1), + Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs), Run: func(cmd *cobra.Command, args []string) { switch args[0] { case "bash": diff --git a/user_guide.md b/user_guide.md index 977306aa..6a686e30 100644 --- a/user_guide.md +++ b/user_guide.md @@ -349,7 +349,7 @@ shown below: ```go var cmd = &cobra.Command{ Short: "hello", - Args: MatchAll(ExactArgs(2), OnlyValidArgs), + Args: cobra.MatchAll(cobra.ExactArgs(2), cobra.OnlyValidArgs), Run: func(cmd *cobra.Command, args []string) { fmt.Println("Hello, World!") }, From 10cf7be9972ee5b5994cf760ecba642309ac8685 Mon Sep 17 00:00:00 2001 From: Marc Khouzam Date: Mon, 24 Oct 2022 11:11:57 -0400 Subject: [PATCH 53/74] Check for group presence after full initialization (#1839) Fixes #1831 By moving the check for help group existence to "ExecuteC()" we no longer need groups to be added before AddCommand() is called. This provides more flexibility to developers and works better with the use of "init()" for command creation. Signed-off-by: Marc Khouzam --- command.go | 21 ++++++++++--- command_test.go | 78 +++++++++++++++++++++++++++++++++++++++++++++++++ user_guide.md | 9 +++--- 3 files changed, 100 insertions(+), 8 deletions(-) diff --git a/command.go b/command.go index 9d5e9cf5..6ff47dd5 100644 --- a/command.go +++ b/command.go @@ -998,6 +998,10 @@ func (c *Command) ExecuteC() (cmd *Command, err error) { // initialize completion at the last point to allow for user overriding c.InitDefaultCompletionCmd() + // Now that all commands have been created, let's make sure all groups + // are properly created also + c.checkCommandGroups() + args := c.args // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155 @@ -1092,6 +1096,19 @@ func (c *Command) ValidateRequiredFlags() error { return nil } +// checkCommandGroups checks if a command has been added to a group that does not exists. +// If so, we panic because it indicates a coding error that should be corrected. +func (c *Command) checkCommandGroups() { + for _, sub := range c.commands { + // if Group is not defined let the developer know right away + if sub.GroupID != "" && !c.ContainsGroup(sub.GroupID) { + panic(fmt.Sprintf("group id '%s' is not defined for subcommand '%s'", sub.GroupID, sub.CommandPath())) + } + + sub.checkCommandGroups() + } +} + // InitDefaultHelpFlag adds default help flag to c. // It is called automatically by executing the c or by calling help and usage. // If c already has help flag, it will do nothing. @@ -1218,10 +1235,6 @@ func (c *Command) AddCommand(cmds ...*Command) { panic("Command can't be a child of itself") } cmds[i].parent = c - // if Group is not defined let the developer know right away - if x.GroupID != "" && !c.ContainsGroup(x.GroupID) { - panic(fmt.Sprintf("Group id '%s' is not defined for subcommand '%s'", x.GroupID, cmds[i].CommandPath())) - } // update max lengths usageLen := len(x.Use) if usageLen > c.commandsMaxUseLen { diff --git a/command_test.go b/command_test.go index 0adec93d..c023bd6e 100644 --- a/command_test.go +++ b/command_test.go @@ -1862,6 +1862,84 @@ func TestAddGroup(t *testing.T) { checkStringContains(t, output, "\nTest group\n cmd") } +func TestWrongGroupFirstLevel(t *testing.T) { + var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun} + + rootCmd.AddGroup(&Group{ID: "group", Title: "Test group"}) + // Use the wrong group ID + rootCmd.AddCommand(&Command{Use: "cmd", GroupID: "wrong", Run: emptyRun}) + + defer func() { + if recover() == nil { + t.Errorf("The code should have panicked due to a missing group") + } + }() + _, err := executeCommand(rootCmd, "--help") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } +} + +func TestWrongGroupNestedLevel(t *testing.T) { + var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun} + var childCmd = &Command{Use: "child", Run: emptyRun} + rootCmd.AddCommand(childCmd) + + childCmd.AddGroup(&Group{ID: "group", Title: "Test group"}) + // Use the wrong group ID + childCmd.AddCommand(&Command{Use: "cmd", GroupID: "wrong", Run: emptyRun}) + + defer func() { + if recover() == nil { + t.Errorf("The code should have panicked due to a missing group") + } + }() + _, err := executeCommand(rootCmd, "child", "--help") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } +} + +func TestWrongGroupForHelp(t *testing.T) { + var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun} + var childCmd = &Command{Use: "child", Run: emptyRun} + rootCmd.AddCommand(childCmd) + + rootCmd.AddGroup(&Group{ID: "group", Title: "Test group"}) + // Use the wrong group ID + rootCmd.SetHelpCommandGroupID("wrong") + + defer func() { + if recover() == nil { + t.Errorf("The code should have panicked due to a missing group") + } + }() + _, err := executeCommand(rootCmd, "--help") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } +} + +func TestWrongGroupForCompletion(t *testing.T) { + var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun} + var childCmd = &Command{Use: "child", Run: emptyRun} + rootCmd.AddCommand(childCmd) + + rootCmd.AddGroup(&Group{ID: "group", Title: "Test group"}) + // Use the wrong group ID + rootCmd.SetCompletionCommandGroupID("wrong") + + defer func() { + if recover() == nil { + t.Errorf("The code should have panicked due to a missing group") + } + }() + _, err := executeCommand(rootCmd, "--help") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } +} + func TestSetOutput(t *testing.T) { c := &Command{} c.SetOutput(nil) diff --git a/user_guide.md b/user_guide.md index 6a686e30..fee9848d 100644 --- a/user_guide.md +++ b/user_guide.md @@ -492,10 +492,11 @@ around it. In fact, you can provide your own if you want. ### Grouping commands in help -Cobra supports grouping of available commands. Groups must be explicitly defined by `AddGroup` and set by -the `GroupId` element of a subcommand. The groups will appear in the same order as they are defined. -If you use the generated `help` or `completion` commands, you can set the group ids by `SetHelpCommandGroupId` -and `SetCompletionCommandGroupId`, respectively. +Cobra supports grouping of available commands in the help output. To group commands, each group must be explicitly +defined using `AddGroup()` on the parent command. Then a subcommand can be added to a group using the `GroupID` element +of that subcommand. The groups will appear in the help output in the same order as they are defined using different +calls to `AddGroup()`. If you use the generated `help` or `completion` commands, you can set their group ids using +`SetHelpCommandGroupId()` and `SetCompletionCommandGroupId()` on the root command, respectively. ### Defining your own help From cc7e235fc26cfd0b5ae36c960f399eea4badaa3e Mon Sep 17 00:00:00 2001 From: mike76-dev <72828450+mike76-dev@users.noreply.github.com> Date: Tue, 1 Nov 2022 14:15:28 +0100 Subject: [PATCH 54/74] Add Sia to projects using Cobra (#1844) --- projects_using_cobra.md | 1 + 1 file changed, 1 insertion(+) diff --git a/projects_using_cobra.md b/projects_using_cobra.md index 99fbd0b8..934b04ab 100644 --- a/projects_using_cobra.md +++ b/projects_using_cobra.md @@ -52,6 +52,7 @@ - [Random](https://github.com/erdaltsksn/random) - [Rclone](https://rclone.org/) - [Scaleway CLI](https://github.com/scaleway/scaleway-cli) +- [Sia](https://github.com/SiaFoundation/siad) - [Skaffold](https://skaffold.dev/) - [Tendermint](https://github.com/tendermint/tendermint) - [Twitch CLI](https://github.com/twitchdev/twitch-cli) From 6b0bd3076cfafd1c108264ed1e4aa0c0fe3f8537 Mon Sep 17 00:00:00 2001 From: Brian Pursley Date: Mon, 7 Nov 2022 23:12:02 -0500 Subject: [PATCH 55/74] fix: don't remove flag value that matches subcommand name (#1781) When the command searches args to find the arg matching a particular subcommand name, it needs to ignore flag values, as it is possible that the value for a flag might match the name of the sub command. This change improves argsMinusFirstX() to ignore flag values when it searches for the X to exclude from the result. --- command.go | 40 +++++++++++++++++----- command_test.go | 89 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 121 insertions(+), 8 deletions(-) diff --git a/command.go b/command.go index 6ff47dd5..1b0b17a2 100644 --- a/command.go +++ b/command.go @@ -655,13 +655,37 @@ Loop: // argsMinusFirstX removes only the first x from args. Otherwise, commands that look like // openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]). -func argsMinusFirstX(args []string, x string) []string { - for i, y := range args { - if x == y { - ret := []string{} - ret = append(ret, args[:i]...) - ret = append(ret, args[i+1:]...) - return ret +// Special care needs to be taken not to remove a flag value. +func (c *Command) argsMinusFirstX(args []string, x string) []string { + if len(args) == 0 { + return args + } + c.mergePersistentFlags() + flags := c.Flags() + +Loop: + for pos := 0; pos < len(args); pos++ { + s := args[pos] + switch { + case s == "--": + // -- means we have reached the end of the parseable args. Break out of the loop now. + break Loop + case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags): + fallthrough + case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags): + // This is a flag without a default value, and an equal sign is not used. Increment pos in order to skip + // over the next arg, because that is the value of this flag. + pos++ + continue + case !strings.HasPrefix(s, "-"): + // This is not a flag or a flag value. Check to see if it matches what we're looking for, and if so, + // return the args, excluding the one at this position. + if s == x { + ret := []string{} + ret = append(ret, args[:pos]...) + ret = append(ret, args[pos+1:]...) + return ret + } } } return args @@ -686,7 +710,7 @@ func (c *Command) Find(args []string) (*Command, []string, error) { cmd := c.findNext(nextSubCmd) if cmd != nil { - return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd)) + return innerfind(cmd, c.argsMinusFirstX(innerArgs, nextSubCmd)) } return c, innerArgs } diff --git a/command_test.go b/command_test.go index c023bd6e..3fd36c7e 100644 --- a/command_test.go +++ b/command_test.go @@ -2603,3 +2603,92 @@ func TestHelpflagCommandExecutedWithoutVersionSet(t *testing.T) { checkStringContains(t, output, HelpFlag) checkStringOmits(t, output, VersionFlag) } + +func TestFind(t *testing.T) { + var foo, bar string + root := &Command{ + Use: "root", + } + root.PersistentFlags().StringVarP(&foo, "foo", "f", "", "") + root.PersistentFlags().StringVarP(&bar, "bar", "b", "something", "") + + child := &Command{ + Use: "child", + } + root.AddCommand(child) + + testCases := []struct { + args []string + expectedFoundArgs []string + }{ + { + []string{"child"}, + []string{}, + }, + { + []string{"child", "child"}, + []string{"child"}, + }, + { + []string{"child", "foo", "child", "bar", "child", "baz", "child"}, + []string{"foo", "child", "bar", "child", "baz", "child"}, + }, + { + []string{"-f", "child", "child"}, + []string{"-f", "child"}, + }, + { + []string{"child", "-f", "child"}, + []string{"-f", "child"}, + }, + { + []string{"-b", "child", "child"}, + []string{"-b", "child"}, + }, + { + []string{"child", "-b", "child"}, + []string{"-b", "child"}, + }, + { + []string{"child", "-b"}, + []string{"-b"}, + }, + { + []string{"-b", "-f", "child", "child"}, + []string{"-b", "-f", "child"}, + }, + { + []string{"-f", "child", "-b", "something", "child"}, + []string{"-f", "child", "-b", "something"}, + }, + { + []string{"-f", "child", "child", "-b"}, + []string{"-f", "child", "-b"}, + }, + { + []string{"-f=child", "-b=something", "child"}, + []string{"-f=child", "-b=something"}, + }, + { + []string{"--foo", "child", "--bar", "something", "child"}, + []string{"--foo", "child", "--bar", "something"}, + }, + } + + for _, tc := range testCases { + t.Run(fmt.Sprintf("%v", tc.args), func(t *testing.T) { + cmd, foundArgs, err := root.Find(tc.args) + if err != nil { + t.Fatal(err) + } + + if cmd != child { + t.Fatal("Expected cmd to be child, but it was not") + } + + if !reflect.DeepEqual(tc.expectedFoundArgs, foundArgs) { + t.Fatalf("Wrong args\nExpected: %v\nGot: %v", tc.expectedFoundArgs, foundArgs) + } + }) + } +} From ad6db7f8f6e485f55b1561df9276fa4d8e278bde Mon Sep 17 00:00:00 2001 From: Brian Pursley Date: Mon, 14 Nov 2022 21:46:57 -0500 Subject: [PATCH 56/74] Create unit test illustrating unknown flag bug (#1854) Created a unit test that tests the unknown flag error message when the unknown flag is located in different arg positions. --- command_test.go | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/command_test.go b/command_test.go index 3fd36c7e..18011325 100644 --- a/command_test.go +++ b/command_test.go @@ -2692,3 +2692,46 @@ func TestFind(t *testing.T) { }) } } + +func TestUnknownFlagShouldReturnSameErrorRegardlessOfArgPosition(t *testing.T) { + testCases := [][]string{ + //{"--unknown", "--namespace", "foo", "child", "--bar"}, // FIXME: This test case fails, returning the error `unknown command "foo" for "root"` instead of the expected error `unknown flag: --unknown` + {"--namespace", "foo", "--unknown", "child", "--bar"}, + {"--namespace", "foo", "child", "--unknown", "--bar"}, + {"--namespace", "foo", "child", "--bar", "--unknown"}, + + {"--unknown", "--namespace=foo", "child", "--bar"}, + {"--namespace=foo", "--unknown", "child", "--bar"}, + {"--namespace=foo", "child", "--unknown", "--bar"}, + {"--namespace=foo", "child", "--bar", "--unknown"}, + + {"--unknown", "--namespace=foo", "child", "--bar=true"}, + {"--namespace=foo", "--unknown", "child", "--bar=true"}, + {"--namespace=foo", "child", "--unknown", "--bar=true"}, + {"--namespace=foo", "child", "--bar=true", "--unknown"}, + } + + root := &Command{ + Use: "root", + Run: emptyRun, + } + root.PersistentFlags().String("namespace", "", "a string flag") + + c := &Command{ + Use: "child", + Run: emptyRun, + } + c.Flags().Bool("bar", false, "a boolean flag") + + root.AddCommand(c) + + for _, tc := range testCases { + t.Run(strings.Join(tc, " "), func(t *testing.T) { + output, err := executeCommand(root, tc...) + if err == nil { + t.Error("expected unknown flag error") + } + checkStringContains(t, output, "unknown flag: --unknown") + }) + } +} From 430549841b79b3731b27df81e2752b729fd4ae43 Mon Sep 17 00:00:00 2001 From: Enrico Candino Date: Tue, 22 Nov 2022 03:04:26 +0100 Subject: [PATCH 57/74] Update stale.yml (#1863) --- .github/workflows/stale.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index 2db5123d..7d06e463 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -28,7 +28,7 @@ jobs: You can: - Make a comment to remove the stale label and show your support. The 60 days reset. - - If an issue has lifecycle/rotten and is closed, comment and ask maintainers if they'd be interseted in reopening" + - If an issue has lifecycle/rotten and is closed, comment and ask maintainers if they'd be interested in reopening" stale-pr-message: "The Cobra project currently lacks enough contributors to adequately respond to all PRs. This bot triages issues and PRs according to the following rules: @@ -39,7 +39,7 @@ jobs: You can: - Make a comment to remove the stale label and show your support. The 60 days reset. - - If a PR has lifecycle/rotten and is closed, comment and ask maintainers if they'd be interseted in reopening." + - If a PR has lifecycle/rotten and is closed, comment and ask maintainers if they'd be interested in reopening." days-before-stale: 60 days-before-close: 30 From c6b99719235fcb18d950f972f27d95fdb0347f02 Mon Sep 17 00:00:00 2001 From: Norman Dankert Date: Fri, 25 Nov 2022 21:47:20 +0100 Subject: [PATCH 58/74] fix: force ForEach-Object to return array in pwsh completion (#1850) Fixes #1847 --- powershell_completions.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/powershell_completions.go b/powershell_completions.go index 004de42e..c9d47e61 100644 --- a/powershell_completions.go +++ b/powershell_completions.go @@ -137,7 +137,7 @@ filter __%[1]s_escapeStringWithSpecialChars { } $Longest = 0 - $Values = $Out | ForEach-Object { + [Array]$Values = $Out | ForEach-Object { #Split the output in name and description `+" $Name, $Description = $_.Split(\"`t\",2)"+` __%[1]s_debug "Name: $Name Description: $Description" From 6200c8e551774046849aafbbc28a74f485e15749 Mon Sep 17 00:00:00 2001 From: Unai Martinez-Corral <38422348+umarcor@users.noreply.github.com> Date: Fri, 25 Nov 2022 20:55:09 +0000 Subject: [PATCH 59/74] Makefile: add target richtest (#1865) Don't require contributors to install richgo but keep it as an option and for CI --- .github/workflows/test.yml | 4 ++-- Makefile | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index a55d39fe..7f047352 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -88,7 +88,7 @@ jobs: go install github.com/kyoh86/richgo"${_version}" go install github.com/mitchellh/gox"${_version}" - - run: RICHGO_FORCE_COLOR=1 PATH=$HOME/go/bin/:$PATH make test + - run: RICHGO_FORCE_COLOR=1 PATH=$HOME/go/bin/:$PATH make richtest test-win: @@ -125,4 +125,4 @@ jobs: go install github.com/kyoh86/richgo@latest go install github.com/mitchellh/gox@latest - - run: RICHGO_FORCE_COLOR=1 PATH=$HOME/go/bin:$PATH make test + - run: RICHGO_FORCE_COLOR=1 PATH=$HOME/go/bin:$PATH make richtest diff --git a/Makefile b/Makefile index c433a01b..0da8d7aa 100644 --- a/Makefile +++ b/Makefile @@ -5,10 +5,6 @@ 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 install github.com/kyoh86/richgo@latest") -endif - .PHONY: fmt lint test install_deps clean default: all @@ -25,6 +21,10 @@ lint: test: install_deps $(info ******************** running tests ********************) + go test -v ./... + +richtest: install_deps + $(info ******************** running tests with kyoh86/richgo ********************) richgo test -v ./... install_deps: From 7bb14400030441629c9c78b2317dfe9f2254e022 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 26 Nov 2022 08:18:05 -0500 Subject: [PATCH 60/74] build(deps): bump golangci/golangci-lint-action from 3.2.0 to 3.3.1 (#1851) Bumps [golangci/golangci-lint-action](https://github.com/golangci/golangci-lint-action) from 3.2.0 to 3.3.1. - [Release notes](https://github.com/golangci/golangci-lint-action/releases) - [Commits](https://github.com/golangci/golangci-lint-action/compare/v3.2.0...v3.3.1) --- updated-dependencies: - dependency-name: golangci/golangci-lint-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 7f047352..71dc5c49 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -49,7 +49,7 @@ jobs: - uses: actions/checkout@v3 - - uses: golangci/golangci-lint-action@v3.2.0 + - uses: golangci/golangci-lint-action@v3.3.1 with: version: latest args: --verbose From a6f198b635c4b18fff81930c40d464904e55b161 Mon Sep 17 00:00:00 2001 From: David Wertenteil Date: Tue, 6 Dec 2022 15:20:58 +0200 Subject: [PATCH 61/74] Update kubescape org (#1874) Signed-off-by: David Wertenteil --- projects_using_cobra.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/projects_using_cobra.md b/projects_using_cobra.md index 934b04ab..4a61f107 100644 --- a/projects_using_cobra.md +++ b/projects_using_cobra.md @@ -26,7 +26,7 @@ - [Istio](https://istio.io) - [Kool](https://github.com/kool-dev/kool) - [Kubernetes](https://kubernetes.io/) -- [Kubescape](https://github.com/armosec/kubescape) +- [Kubescape](https://github.com/kubescape/kubescape) - [KubeVirt](https://github.com/kubevirt/kubevirt) - [Linkerd](https://linkerd.io/) - [Mattermost-server](https://github.com/mattermost/mattermost-server) From 923592041e4ae38e2ae5c3cc66c3eb1e0c27261f Mon Sep 17 00:00:00 2001 From: Unai Martinez-Corral <38422348+umarcor@users.noreply.github.com> Date: Fri, 9 Dec 2022 21:57:19 +0000 Subject: [PATCH 62/74] ci: deprecate go 1.15 (#1866) Remove testing for go 1.15 to allow CI to pass, but don't force projects to upgrade. --- .github/workflows/test.yml | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 71dc5c49..3b3d365e 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -63,7 +63,6 @@ jobs: - ubuntu - macOS go: - - 15 - 16 - 17 - 18 @@ -81,12 +80,8 @@ jobs: - run: | export GOBIN=$HOME/go/bin - case "${{ matrix.go }}" in - 14|15) _version='';; - *) _version='@latest';; - esac - go install github.com/kyoh86/richgo"${_version}" - go install github.com/mitchellh/gox"${_version}" + go install github.com/kyoh86/richgo@latest + go install github.com/mitchellh/gox@latest - run: RICHGO_FORCE_COLOR=1 PATH=$HOME/go/bin/:$PATH make richtest From f25a3c6e0b4220c616a3b342b57b055c1256d318 Mon Sep 17 00:00:00 2001 From: Yash Ladha <18033231+yashLadha@users.noreply.github.com> Date: Thu, 15 Dec 2022 16:09:50 +0530 Subject: [PATCH 63/74] fix: conflict import name with variable (#1879) `template` is an import in `cobra.go` file and also used as a variable name, which masks the library in the scope of that function. --- cobra.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cobra.go b/cobra.go index fe44bc8a..841cda0c 100644 --- a/cobra.go +++ b/cobra.go @@ -167,8 +167,8 @@ func appendIfNotPresent(s, stringToAppend string) string { // rpad adds padding to the right of a string. func rpad(s string, padding int) string { - template := fmt.Sprintf("%%-%ds", padding) - return fmt.Sprintf(template, s) + formattedString := fmt.Sprintf("%%-%ds", padding) + return fmt.Sprintf(formattedString, s) } // tmpl executes the given template text on data, writing the result to w. From fdffa5a4c760e30a38e596299b91c328ffd461bc Mon Sep 17 00:00:00 2001 From: Seonghyeon Cho Date: Sat, 24 Dec 2022 05:54:16 +0900 Subject: [PATCH 64/74] Update badge route (#1884) Based on https://github.com/badges/shields/issues/8671 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7cc726be..063f31a4 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Cobra is used in many Go projects such as [Kubernetes](https://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) +[![](https://img.shields.io/github/actions/workflow/status/spf13/cobra/test.yml?branch=main&longCache=true&label=Test&logo=github%20actions&logoColor=fff)](https://github.com/spf13/cobra/actions?query=workflow%3ATest) [![Go Reference](https://pkg.go.dev/badge/github.com/spf13/cobra.svg)](https://pkg.go.dev/github.com/spf13/cobra) [![Go Report Card](https://goreportcard.com/badge/github.com/spf13/cobra)](https://goreportcard.com/report/github.com/spf13/cobra) [![Slack](https://img.shields.io/badge/Slack-cobra-brightgreen)](https://gophers.slack.com/archives/CD3LP1199) From bf11ab6321f2831be5390fdd71ab0bb2edbd9ed5 Mon Sep 17 00:00:00 2001 From: Yash Ladha <18033231+yashLadha@users.noreply.github.com> Date: Mon, 26 Dec 2022 01:38:39 +0530 Subject: [PATCH 65/74] fix: func name in doc strings (#1885) Corrected the function name at the start of doc strings, as per the convention outlined in official go documentation: https://go.dev/blog/godoc --- args.go | 2 +- bash_completions.go | 2 +- command.go | 10 +++++----- completions.go | 2 +- doc/rest_docs.go | 4 ++-- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/args.go b/args.go index 2c1f99e7..2f4056c8 100644 --- a/args.go +++ b/args.go @@ -21,7 +21,7 @@ import ( type PositionalArgs func(cmd *Command, args []string) error -// Legacy arg validation has the following behaviour: +// legacyArgs validation has the following behaviour: // - root commands with no subcommands can take arbitrary arguments // - root commands with subcommands will do subcommand validity checking // - subcommands will always accept arbitrary arguments diff --git a/bash_completions.go b/bash_completions.go index 3acdb279..a9f4e4f2 100644 --- a/bash_completions.go +++ b/bash_completions.go @@ -532,7 +532,7 @@ func writeLocalNonPersistentFlag(buf io.StringWriter, flag *pflag.Flag) { } } -// Setup annotations for go completions for registered flags +// prepareCustomAnnotationsForFlags setup annotations for go completions for registered flags func prepareCustomAnnotationsForFlags(cmd *Command) { flagCompletionMutex.RLock() defer flagCompletionMutex.RUnlock() diff --git a/command.go b/command.go index 1b0b17a2..f032dbc4 100644 --- a/command.go +++ b/command.go @@ -35,7 +35,7 @@ const FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra" // FParseErrWhitelist configures Flag parse errors to be ignored type FParseErrWhitelist flag.ParseErrorsWhitelist -// Structure to manage groups for commands +// Group Structure to manage groups for commands type Group struct { ID string Title string @@ -47,7 +47,7 @@ type Group struct { // definition to ensure usability. type Command struct { // Use is the one-line usage message. - // Recommended syntax is as follow: + // Recommended syntax is as follows: // [ ] identifies an optional argument. Arguments that are not enclosed in brackets are required. // ... indicates that you can specify multiple values for the previous argument. // | indicates mutually exclusive information. You can use the argument to the left of the separator or the @@ -321,7 +321,7 @@ func (c *Command) SetHelpCommand(cmd *Command) { c.helpCommand = cmd } -// SetHelpCommandGroup sets the group id of the help command. +// SetHelpCommandGroupID sets the group id of the help command. func (c *Command) SetHelpCommandGroupID(groupID string) { if c.helpCommand != nil { c.helpCommand.GroupID = groupID @@ -330,7 +330,7 @@ func (c *Command) SetHelpCommandGroupID(groupID string) { c.helpCommandGroupID = groupID } -// SetCompletionCommandGroup sets the group id of the completion command. +// SetCompletionCommandGroupID sets the group id of the completion command. func (c *Command) SetCompletionCommandGroupID(groupID string) { // completionCommandGroupID is used if no completion command is defined by the user c.Root().completionCommandGroupID = groupID @@ -1296,7 +1296,7 @@ func (c *Command) AllChildCommandsHaveGroup() bool { return true } -// ContainGroups return if groupID exists in the list of command groups. +// ContainsGroup return if groupID exists in the list of command groups. func (c *Command) ContainsGroup(groupID string) bool { for _, x := range c.commandgroups { if x.ID == groupID { diff --git a/completions.go b/completions.go index e8a0206d..8341959a 100644 --- a/completions.go +++ b/completions.go @@ -169,7 +169,7 @@ func (d ShellCompDirective) string() string { return strings.Join(directives, ", ") } -// Adds a special hidden command that can be used to request custom completions. +// initCompleteCmd adds a special hidden command that can be used to request custom completions. func (c *Command) initCompleteCmd(args []string) { completeCmd := &Command{ Use: fmt.Sprintf("%s [command-line]", ShellCompRequestCmd), diff --git a/doc/rest_docs.go b/doc/rest_docs.go index d6589065..bb0f8ec4 100644 --- a/doc/rest_docs.go +++ b/doc/rest_docs.go @@ -48,7 +48,7 @@ func printOptionsReST(buf *bytes.Buffer, cmd *cobra.Command, name string) error return nil } -// linkHandler for default ReST hyperlink markup +// defaultLinkHandler for default ReST hyperlink markup func defaultLinkHandler(name, ref string) string { return fmt.Sprintf("`%s <%s.rst>`_", name, ref) } @@ -169,7 +169,7 @@ func GenReSTTreeCustom(cmd *cobra.Command, dir string, filePrepender func(string return nil } -// adapted from: https://github.com/kr/text/blob/main/indent.go +// indentString adapted from: https://github.com/kr/text/blob/main/indent.go func indentString(s, p string) string { var res []byte b := []byte(s) From b4f979ae352828a0153281b590771ce9588d67f8 Mon Sep 17 00:00:00 2001 From: Dominik Roos Date: Tue, 3 Jan 2023 01:58:36 +0100 Subject: [PATCH 66/74] completions: do not detect arguments with dash as 2nd char as flag (#1817) Fixes #1816 Previously, arguments with a dash as the second character (e.g., 1-ff00:0:1) were detected as a flag by mistake. This resulted in auto completion misbehaving if such an argument was last in the argument list during invocation. --- command.go | 2 +- completions_test.go | 64 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 1 deletion(-) diff --git a/command.go b/command.go index f032dbc4..b6e3f4a1 100644 --- a/command.go +++ b/command.go @@ -692,7 +692,7 @@ Loop: } func isFlagArg(arg string) bool { - return ((len(arg) >= 3 && arg[1] == '-') || + return ((len(arg) >= 3 && arg[0:2] == "--") || (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-')) } diff --git a/completions_test.go b/completions_test.go index abac12e4..2364ed2e 100644 --- a/completions_test.go +++ b/completions_test.go @@ -3115,3 +3115,67 @@ func TestCompletionCobraFlags(t *testing.T) { }) } } + +func TestArgsNotDetectedAsFlagsCompletionInGo(t *testing.T) { + // Regression test that ensures the bug described in + // https://github.com/spf13/cobra/issues/1816 does not occur anymore. + + root := Command{ + Use: "root", + ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { + return []string{"service", "1-123", "11-123"}, ShellCompDirectiveNoFileComp + }, + } + + completion := `service +1-123 +11-123 +:4 +Completion ended with directive: ShellCompDirectiveNoFileComp +` + + testcases := []struct { + desc string + args []string + expectedOutput string + }{ + { + desc: "empty", + args: []string{""}, + expectedOutput: completion, + }, + { + desc: "service only", + args: []string{"service", ""}, + expectedOutput: completion, + }, + { + desc: "service last", + args: []string{"1-123", "service", ""}, + expectedOutput: completion, + }, + { + desc: "two digit prefixed dash last", + args: []string{"service", "11-123", ""}, + expectedOutput: completion, + }, + { + desc: "one digit prefixed dash last", + args: []string{"service", "1-123", ""}, + expectedOutput: completion, + }, + } + for _, tc := range testcases { + t.Run(tc.desc, func(t *testing.T) { + args := []string{ShellCompNoDescRequestCmd} + args = append(args, tc.args...) + output, err := executeCommand(&root, args...) + switch { + case err == nil && output != tc.expectedOutput: + t.Errorf("expected: %q, got: %q", tc.expectedOutput, output) + case err != nil: + t.Errorf("Unexpected error %q", err) + } + }) + } +} From 4fa4fdf5cd34cb78973561d077461caea8eeb48a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 3 Jan 2023 02:43:06 +0000 Subject: [PATCH 67/74] build(deps): bump github.com/inconshreveable/mousetrap (#1872) --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index a1309e53..6361d742 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.15 require ( github.com/cpuguy83/go-md2man/v2 v2.0.2 - github.com/inconshreveable/mousetrap v1.0.1 + github.com/inconshreveable/mousetrap v1.1.0 github.com/spf13/pflag v1.0.5 gopkg.in/yaml.v3 v3.0.1 ) diff --git a/go.sum b/go.sum index a8c544e2..5ccb69dd 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,7 @@ github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= -github.com/inconshreveable/mousetrap v1.0.1 h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7Pgzkat/bFNc= -github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= From d022c0fe2b70e61f7edc264ef5639cdf71e9ceb3 Mon Sep 17 00:00:00 2001 From: Shihta Kuan Date: Tue, 31 Jan 2023 01:58:20 +0800 Subject: [PATCH 68/74] Add documentation about disabling completion descriptions (#1901) --- shell_completions.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/shell_completions.md b/shell_completions.md index 286c2525..f3285e31 100644 --- a/shell_completions.md +++ b/shell_completions.md @@ -385,6 +385,19 @@ or ```go ValidArgs: []string{"bash\tCompletions for bash", "zsh\tCompletions for zsh"} ``` + +If you don't want to show descriptions in the completions, you can add `--no-descriptions` to the default `completion` command to disable them, like: + +```bash +$ source <(helm completion bash) +$ helm completion [tab][tab] +bash (generate autocompletion script for bash) powershell (generate autocompletion script for powershell) +fish (generate autocompletion script for fish) zsh (generate autocompletion script for zsh) + +$ source <(helm completion bash --no-descriptions) +$ helm completion [tab][tab] +bash fish powershell zsh +``` ## Bash completions ### Dependencies From 8b8ee8754cb7ad722506484737722720732992b6 Mon Sep 17 00:00:00 2001 From: janhn Date: Mon, 6 Feb 2023 12:15:40 +0100 Subject: [PATCH 69/74] Improve MarkFlagsMutuallyExclusive example in User Guide (#1904) --- user_guide.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/user_guide.md b/user_guide.md index fee9848d..00b53d03 100644 --- a/user_guide.md +++ b/user_guide.md @@ -313,8 +313,8 @@ rootCmd.MarkFlagsRequiredTogether("username", "password") You can also prevent different flags from being provided together if they represent mutually exclusive options such as specifying an output format as either `--json` or `--yaml` but never both: ```go -rootCmd.Flags().BoolVar(&u, "json", false, "Output in JSON") -rootCmd.Flags().BoolVar(&pw, "yaml", false, "Output in YAML") +rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON") +rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML") rootCmd.MarkFlagsMutuallyExclusive("json", "yaml") ``` From 87ebcd8f9884bfe15a996767ef1636787773a8b7 Mon Sep 17 00:00:00 2001 From: Ggg6542 <465806+gusega@users.noreply.github.com> Date: Thu, 9 Feb 2023 03:11:53 +0100 Subject: [PATCH 70/74] Update shell_completions.md (#1907) align documentation with the code : completions.go:452 --- shell_completions.md | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/shell_completions.md b/shell_completions.md index f3285e31..6c48f3e4 100644 --- a/shell_completions.md +++ b/shell_completions.md @@ -162,16 +162,7 @@ cmd := &cobra.Command{ } ``` -The aliases are not shown to the user on tab completion, but they are accepted as valid nouns by -the completion algorithm if entered manually, e.g. in: - -```bash -$ kubectl get rc [tab][tab] -backend frontend database -``` - -Note that without declaring `rc` as an alias, the completion algorithm would not know to show the list of -replication controllers following `rc`. +The aliases are shown to the user on tab completion only if no completions were found within sub-commands or `ValidArgs`. ### Dynamic completion of nouns From e839bb342f7914fd1bf62041cebd801292e2ccf8 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 12 Feb 2023 01:27:13 +0000 Subject: [PATCH 71/74] build(deps): bump golangci/golangci-lint-action from 3.3.1 to 3.4.0 (#1902) --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 3b3d365e..b4307724 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -49,7 +49,7 @@ jobs: - uses: actions/checkout@v3 - - uses: golangci/golangci-lint-action@v3.3.1 + - uses: golangci/golangci-lint-action@v3.4.0 with: version: latest args: --verbose From a516d4132c811a4101ce6d99ac12671217d1ac37 Mon Sep 17 00:00:00 2001 From: John McBride Date: Mon, 13 Feb 2023 20:49:03 -0700 Subject: [PATCH 72/74] Removes stale bot from GitHub action (#1908) Signed-off-by: John McBride --- .github/workflows/stale.yml | 56 ------------------------------------- 1 file changed, 56 deletions(-) delete mode 100644 .github/workflows/stale.yml diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml deleted file mode 100644 index 7d06e463..00000000 --- a/.github/workflows/stale.yml +++ /dev/null @@ -1,56 +0,0 @@ -name: Mark stale issues and pull requests - -on: - schedule: - - cron: "0 0 * * *" - -permissions: - contents: read - -jobs: - stale: - - permissions: - issues: write # for actions/stale to close stale issues - pull-requests: write # for actions/stale to close stale PRs - runs-on: ubuntu-latest - - steps: - - uses: actions/stale@v6 - with: - repo-token: ${{ secrets.GITHUB_TOKEN }} - stale-issue-message: "The Cobra project currently lacks enough contributors to adequately respond to all issues. - This bot triages issues and PRs according to the following rules: - - - After 60d of inactivity, lifecycle/stale is applied. - - After 30d of inactivity since lifecycle/stale was applied, lifecycle/rotten is applied and the issue is closed. - - You can: - - - Make a comment to remove the stale label and show your support. The 60 days reset. - - If an issue has lifecycle/rotten and is closed, comment and ask maintainers if they'd be interested in reopening" - - stale-pr-message: "The Cobra project currently lacks enough contributors to adequately respond to all PRs. - This bot triages issues and PRs according to the following rules: - - - After 60d of inactivity, lifecycle/stale is applied. - - After 30d of inactivity since lifecycle/stale was applied, lifecycle/rotten is applied and the PR is closed. - - You can: - - - Make a comment to remove the stale label and show your support. The 60 days reset. - - If a PR has lifecycle/rotten and is closed, comment and ask maintainers if they'd be interested in reopening." - - days-before-stale: 60 - days-before-close: 30 - stale-issue-label: 'lifecycle/stale' - stale-pr-label: 'lifecycle/stale' - exempt-issue-labels: 'lifecycle/frozen' - exempt-pr-labels: 'lifecycle/frozen' - close-issue-label: 'lifecycle/rotten' - close-pr-label: 'lifecycle/rotten' - - # Since cobra has so many legacy issues and PRs that need to be triaged, - # only label new PRs and issues. - start-date: '2022-02-01T00:00:00Z' - From 3daa4b9c36617509a756832a3d0ee2b6f4b8c129 Mon Sep 17 00:00:00 2001 From: Gyanendra Mishra Date: Sat, 25 Feb 2023 20:57:12 +0000 Subject: [PATCH 73/74] Add keeporder to shell completion (#1903) This allows programs to request the shell to maintain the order of completions that was returned by the program --- bash_completionsV2.go | 18 ++++++++-- completions.go | 7 ++++ fish_completions.go | 76 ++++++++++++++++++++++++++++++++++----- powershell_completions.go | 10 ++++-- shell_completions.md | 4 +++ zsh_completions.go | 14 +++++--- 6 files changed, 112 insertions(+), 17 deletions(-) diff --git a/bash_completionsV2.go b/bash_completionsV2.go index 78f43b91..5a38e38d 100644 --- a/bash_completionsV2.go +++ b/bash_completionsV2.go @@ -101,6 +101,7 @@ __%[1]s_process_completion_results() { local shellCompDirectiveNoFileComp=%[5]d local shellCompDirectiveFilterFileExt=%[6]d local shellCompDirectiveFilterDirs=%[7]d + local shellCompDirectiveKeepOrder=%[8]d if (((directive & shellCompDirectiveError) != 0)); then # Error code. No completion. @@ -115,6 +116,19 @@ __%[1]s_process_completion_results() { __%[1]s_debug "No space directive not supported in this version of bash" fi fi + if (((directive & shellCompDirectiveKeepOrder) != 0)); then + if [[ $(type -t compopt) == builtin ]]; then + # no sort isn't supported for bash less than < 4.4 + if [[ ${BASH_VERSINFO[0]} -lt 4 || ( ${BASH_VERSINFO[0]} -eq 4 && ${BASH_VERSINFO[1]} -lt 4 ) ]]; then + __%[1]s_debug "No sort directive not supported in this version of bash" + else + __%[1]s_debug "Activating keep order" + compopt -o nosort + fi + else + __%[1]s_debug "No sort directive not supported in this version of bash" + fi + fi if (((directive & shellCompDirectiveNoFileComp) != 0)); then if [[ $(type -t compopt) == builtin ]]; then __%[1]s_debug "Activating no file completion" @@ -183,7 +197,7 @@ __%[1]s_process_completion_results() { # Separate activeHelp lines from real completions. # Fills the $activeHelp and $completions arrays. __%[1]s_extract_activeHelp() { - local activeHelpMarker="%[8]s" + local activeHelpMarker="%[9]s" local endIndex=${#activeHelpMarker} while IFS='' read -r comp; do @@ -360,7 +374,7 @@ fi # ex: ts=4 sw=4 et filetype=sh `, name, compCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, + ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpMarker)) } diff --git a/completions.go b/completions.go index 8341959a..c7b457eb 100644 --- a/completions.go +++ b/completions.go @@ -77,6 +77,10 @@ const ( // obtain the same behavior but only for flags. ShellCompDirectiveFilterDirs + // ShellCompDirectiveKeepOrder indicates that the shell should preserve the order + // in which the completions are provided + ShellCompDirectiveKeepOrder + // =========================================================================== // All directives using iota should be above this one. @@ -159,6 +163,9 @@ func (d ShellCompDirective) string() string { if d&ShellCompDirectiveFilterDirs != 0 { directives = append(directives, "ShellCompDirectiveFilterDirs") } + if d&ShellCompDirectiveKeepOrder != 0 { + directives = append(directives, "ShellCompDirectiveKeepOrder") + } if len(directives) == 0 { directives = append(directives, "ShellCompDirectiveDefault") } diff --git a/fish_completions.go b/fish_completions.go index 97112a17..32c4bea0 100644 --- a/fish_completions.go +++ b/fish_completions.go @@ -53,7 +53,7 @@ function __%[1]s_perform_completion __%[1]s_debug "last arg: $lastArg" # Disable ActiveHelp which is not supported for fish shell - set -l requestComp "%[9]s=0 $args[1] %[3]s $args[2..-1] $lastArg" + set -l requestComp "%[10]s=0 $args[1] %[3]s $args[2..-1] $lastArg" __%[1]s_debug "Calling $requestComp" set -l results (eval $requestComp 2> /dev/null) @@ -89,6 +89,60 @@ function __%[1]s_perform_completion printf "%%s\n" "$directiveLine" end +# this function limits calls to __%[1]s_perform_completion, by caching the result behind $__%[1]s_perform_completion_once_result +function __%[1]s_perform_completion_once + __%[1]s_debug "Starting __%[1]s_perform_completion_once" + + if test -n "$__%[1]s_perform_completion_once_result" + __%[1]s_debug "Seems like a valid result already exists, skipping __%[1]s_perform_completion" + return 0 + end + + set --global __%[1]s_perform_completion_once_result (__%[1]s_perform_completion) + if test -z "$__%[1]s_perform_completion_once_result" + __%[1]s_debug "No completions, probably due to a failure" + return 1 + end + + __%[1]s_debug "Performed completions and set __%[1]s_perform_completion_once_result" + return 0 +end + +# this function is used to clear the $__%[1]s_perform_completion_once_result variable after completions are run +function __%[1]s_clear_perform_completion_once_result + __%[1]s_debug "" + __%[1]s_debug "========= clearing previously set __%[1]s_perform_completion_once_result variable ==========" + set --erase __%[1]s_perform_completion_once_result + __%[1]s_debug "Succesfully erased the variable __%[1]s_perform_completion_once_result" +end + +function __%[1]s_requires_order_preservation + __%[1]s_debug "" + __%[1]s_debug "========= checking if order preservation is required ==========" + + __%[1]s_perform_completion_once + if test -z "$__%[1]s_perform_completion_once_result" + __%[1]s_debug "Error determining if order preservation is required" + return 1 + end + + set -l directive (string sub --start 2 $__%[1]s_perform_completion_once_result[-1]) + __%[1]s_debug "Directive is: $directive" + + set -l shellCompDirectiveKeepOrder %[9]d + set -l keeporder (math (math --scale 0 $directive / $shellCompDirectiveKeepOrder) %% 2) + __%[1]s_debug "Keeporder is: $keeporder" + + if test $keeporder -ne 0 + __%[1]s_debug "This does require order preservation" + return 0 + end + + __%[1]s_debug "This doesn't require order preservation" + return 1 +end + + # This function does two things: # - Obtain the completions and store them in the global __%[1]s_comp_results # - Return false if file completion should be performed @@ -99,17 +153,17 @@ function __%[1]s_prepare_completions # Start fresh set --erase __%[1]s_comp_results - set -l results (__%[1]s_perform_completion) - __%[1]s_debug "Completion results: $results" + __%[1]s_perform_completion_once + __%[1]s_debug "Completion results: $__%[1]s_perform_completion_once_result" - if test -z "$results" + if test -z "$__%[1]s_perform_completion_once_result" __%[1]s_debug "No completion, probably due to a failure" # Might as well do file completion, in case it helps return 1 end - set -l directive (string sub --start 2 $results[-1]) - set --global __%[1]s_comp_results $results[1..-2] + set -l directive (string sub --start 2 $__%[1]s_perform_completion_once_result[-1]) + set --global __%[1]s_comp_results $__%[1]s_perform_completion_once_result[1..-2] __%[1]s_debug "Completions are: $__%[1]s_comp_results" __%[1]s_debug "Directive is: $directive" @@ -205,13 +259,17 @@ end # Remove any pre-existing completions for the program since we will be handling all of them. complete -c %[2]s -e +# this will get called after the two calls below and clear the $__%[1]s_perform_completion_once_result global +complete -c %[2]s -n '__%[1]s_clear_perform_completion_once_result' # The call to __%[1]s_prepare_completions will setup __%[1]s_comp_results # which provides the program's completion choices. -complete -c %[2]s -n '__%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results' - +# If this doesn't require order preservation, we don't use the -k flag +complete -c %[2]s -n 'not __%[1]s_requires_order_preservation && __%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results' +# otherwise we use the -k flag +complete -k -c %[2]s -n '__%[1]s_requires_order_preservation && __%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results' `, nameForVar, name, compCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name))) + ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpEnvVar(name))) } // GenFishCompletion generates fish completion file and writes to the passed writer. diff --git a/powershell_completions.go b/powershell_completions.go index c9d47e61..c766fc78 100644 --- a/powershell_completions.go +++ b/powershell_completions.go @@ -77,6 +77,7 @@ filter __%[1]s_escapeStringWithSpecialChars { $ShellCompDirectiveNoFileComp=%[6]d $ShellCompDirectiveFilterFileExt=%[7]d $ShellCompDirectiveFilterDirs=%[8]d + $ShellCompDirectiveKeepOrder=%[9]d # Prepare the command to request completions for the program. # Split the command at the first space to separate the program and arguments. @@ -112,7 +113,7 @@ filter __%[1]s_escapeStringWithSpecialChars { __%[1]s_debug "Calling $RequestComp" # First disable ActiveHelp which is not supported for Powershell - $env:%[9]s=0 + $env:%[10]s=0 #call the command store the output in $out and redirect stderr and stdout to null # $Out is an array contains each line per element @@ -182,6 +183,11 @@ filter __%[1]s_escapeStringWithSpecialChars { } } + # we sort the values in ascending order by name if keep order isn't passed + if (($Directive -band $ShellCompDirectiveKeepOrder) -eq 0 ) { + $Values = $Values | Sort-Object -Property Name + } + if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) { __%[1]s_debug "ShellCompDirectiveNoFileComp is called" @@ -267,7 +273,7 @@ filter __%[1]s_escapeStringWithSpecialChars { Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock $__%[2]sCompleterBlock `, name, nameForVar, compCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name))) + ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpEnvVar(name))) } func (c *Command) genPowerShellCompletion(w io.Writer, includeDesc bool) error { diff --git a/shell_completions.md b/shell_completions.md index 6c48f3e4..065c0621 100644 --- a/shell_completions.md +++ b/shell_completions.md @@ -228,6 +228,10 @@ ShellCompDirectiveFilterFileExt // return []string{"themes"}, ShellCompDirectiveFilterDirs // ShellCompDirectiveFilterDirs + +// ShellCompDirectiveKeepOrder indicates that the shell should preserve the order +// in which the completions are provided +ShellCompDirectiveKeepOrder ``` ***Note***: When using the `ValidArgsFunction`, Cobra will call your registered function after having parsed all flags and arguments provided in the command-line. You therefore don't need to do this parsing yourself. For example, when a user calls `helm status --namespace my-rook-ns [tab][tab]`, Cobra will call your registered `ValidArgsFunction` after having parsed the `--namespace` flag, as it would have done when calling the `RunE` function. diff --git a/zsh_completions.go b/zsh_completions.go index 84cec76f..29bcb570 100644 --- a/zsh_completions.go +++ b/zsh_completions.go @@ -108,8 +108,9 @@ _%[1]s() local shellCompDirectiveNoFileComp=%[5]d local shellCompDirectiveFilterFileExt=%[6]d local shellCompDirectiveFilterDirs=%[7]d + local shellCompDirectiveKeepOrder=%[8]d - local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace + local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace keepOrder local -a completions __%[1]s_debug "\n========= starting completion logic ==========" @@ -177,7 +178,7 @@ _%[1]s() return fi - local activeHelpMarker="%[8]s" + local activeHelpMarker="%[9]s" local endIndex=${#activeHelpMarker} local startIndex=$((${#activeHelpMarker}+1)) local hasActiveHelp=0 @@ -227,6 +228,11 @@ _%[1]s() noSpace="-S ''" fi + if [ $((directive & shellCompDirectiveKeepOrder)) -ne 0 ]; then + __%[1]s_debug "Activating keep order." + keepOrder="-V" + fi + if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then # File extension filtering local filteringCmd @@ -262,7 +268,7 @@ _%[1]s() return $result else __%[1]s_debug "Calling _describe" - if eval _describe "completions" completions $flagPrefix $noSpace; then + if eval _describe $keepOrder "completions" completions $flagPrefix $noSpace; then __%[1]s_debug "_describe found some completions" # Return the success of having called _describe @@ -296,6 +302,6 @@ if [ "$funcstack[1]" = "_%[1]s" ]; then fi `, name, compCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, + ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpMarker)) } From 567ea8ebc9b4385ae671486415cd203fc2a3bab9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Old=C5=99ich=20Jedli=C4=8Dka?= Date: Sat, 25 Feb 2023 22:30:37 +0100 Subject: [PATCH 74/74] Add support for PowerShell 7.2+ (#1916) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PowerShell 7.2 has changed the way arguments are passed to executables. This was originally an experimental feature in 7.2, but as of 7.3 it is built-in. A simple "" is now sufficient for passing empty arguments, no back-tick escaping is required. Fixes #1849 Signed-off-by: Oldřich Jedlička Co-authored-by: Oldřich Jedlička --- powershell_completions.go | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/powershell_completions.go b/powershell_completions.go index c766fc78..927733b3 100644 --- a/powershell_completions.go +++ b/powershell_completions.go @@ -107,8 +107,17 @@ filter __%[1]s_escapeStringWithSpecialChars { # 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\" + ' `\"`\"'"+` + # PowerShell 7.2+ changed the way how the arguments are passed to executables, + # so for pre-7.2 or when Legacy argument passing is enabled we need to use +`+" # `\"`\" to pass an empty argument, a \"\" or '' does not work!!!"+` + if ($PSVersionTable.PsVersion -lt [version]'7.2.0' -or + ($PSVersionTable.PsVersion -lt [version]'7.3.0' -and -not [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -or + (($PSVersionTable.PsVersion -ge [version]'7.3.0' -or [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -and + $PSNativeCommandArgumentPassing -eq 'Legacy')) { +`+" $RequestComp=\"$RequestComp\" + ' `\"`\"'"+` + } else { + $RequestComp="$RequestComp" + ' ""' + } } __%[1]s_debug "Calling $RequestComp"