Skip to content
Myr

Add Active Help support (#1482)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Marc Khouzam · committed by GitHub · parent 7dc8b00 · Browse files · 15 files+776 added−15 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

15 files+776 added−15 removed

  • other:+776 added−15 removed

15 files+776 added−15 removed

added:active_help_test.go+386 added
1package cobra23import (4 "fmt"5 "os"6 "strings"7 "testing"8)910const (11 activeHelpMessage = "This is an activeHelp message"12 activeHelpMessage2 = "This is the rest of the activeHelp message"13)1415func TestActiveHelpAlone(t *testing.T) {16 rootCmd := &Command{17 Use: "root",18 Run: emptyRun,19 }2021 activeHelpFunc := func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {22 comps := AppendActiveHelp(nil, activeHelpMessage)23 return comps, ShellCompDirectiveDefault24 }2526 // Test that activeHelp can be added to a root command27 rootCmd.ValidArgsFunction = activeHelpFunc2829 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")30 if err != nil {31 t.Errorf("Unexpected error: %v", err)32 }3334 expected := strings.Join([]string{35 fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),36 ":0",37 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")3839 if output != expected {40 t.Errorf("expected: %q, got: %q", expected, output)41 }4243 rootCmd.ValidArgsFunction = nil4445 // Test that activeHelp can be added to a child command46 childCmd := &Command{47 Use: "thechild",48 Short: "The child command",49 Run: emptyRun,50 }51 rootCmd.AddCommand(childCmd)5253 childCmd.ValidArgsFunction = activeHelpFunc5455 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")56 if err != nil {57 t.Errorf("Unexpected error: %v", err)58 }5960 expected = strings.Join([]string{61 fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),62 ":0",63 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")6465 if output != expected {66 t.Errorf("expected: %q, got: %q", expected, output)67 }68}6970func TestActiveHelpWithComps(t *testing.T) {71 rootCmd := &Command{72 Use: "root",73 Run: emptyRun,74 }7576 childCmd := &Command{77 Use: "thechild",78 Short: "The child command",79 Run: emptyRun,80 }81 rootCmd.AddCommand(childCmd)8283 // Test that activeHelp can be added following other completions84 childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {85 comps := []string{"first", "second"}86 comps = AppendActiveHelp(comps, activeHelpMessage)87 return comps, ShellCompDirectiveDefault88 }8990 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")91 if err != nil {92 t.Errorf("Unexpected error: %v", err)93 }9495 expected := strings.Join([]string{96 "first",97 "second",98 fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),99 ":0",100 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")101102 if output != expected {103 t.Errorf("expected: %q, got: %q", expected, output)104 }105106 // Test that activeHelp can be added preceding other completions107 childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {108 var comps []string109 comps = AppendActiveHelp(comps, activeHelpMessage)110 comps = append(comps, []string{"first", "second"}...)111 return comps, ShellCompDirectiveDefault112 }113114 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")115 if err != nil {116 t.Errorf("Unexpected error: %v", err)117 }118119 expected = strings.Join([]string{120 fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),121 "first",122 "second",123 ":0",124 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")125126 if output != expected {127 t.Errorf("expected: %q, got: %q", expected, output)128 }129130 // Test that activeHelp can be added interleaved with other completions131 childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {132 comps := []string{"first"}133 comps = AppendActiveHelp(comps, activeHelpMessage)134 comps = append(comps, "second")135 return comps, ShellCompDirectiveDefault136 }137138 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")139 if err != nil {140 t.Errorf("Unexpected error: %v", err)141 }142143 expected = strings.Join([]string{144 "first",145 fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),146 "second",147 ":0",148 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")149150 if output != expected {151 t.Errorf("expected: %q, got: %q", expected, output)152 }153}154155func TestMultiActiveHelp(t *testing.T) {156 rootCmd := &Command{157 Use: "root",158 Run: emptyRun,159 }160161 childCmd := &Command{162 Use: "thechild",163 Short: "The child command",164 Run: emptyRun,165 }166 rootCmd.AddCommand(childCmd)167168 // Test that multiple activeHelp message can be added169 childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {170 comps := AppendActiveHelp(nil, activeHelpMessage)171 comps = AppendActiveHelp(comps, activeHelpMessage2)172 return comps, ShellCompDirectiveNoFileComp173 }174175 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")176 if err != nil {177 t.Errorf("Unexpected error: %v", err)178 }179180 expected := strings.Join([]string{181 fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),182 fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage2),183 ":4",184 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")185186 if output != expected {187 t.Errorf("expected: %q, got: %q", expected, output)188 }189190 // Test that multiple activeHelp messages can be used along with completions191 childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {192 comps := []string{"first"}193 comps = AppendActiveHelp(comps, activeHelpMessage)194 comps = append(comps, "second")195 comps = AppendActiveHelp(comps, activeHelpMessage2)196 return comps, ShellCompDirectiveNoFileComp197 }198199 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")200 if err != nil {201 t.Errorf("Unexpected error: %v", err)202 }203204 expected = strings.Join([]string{205 "first",206 fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),207 "second",208 fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage2),209 ":4",210 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")211212 if output != expected {213 t.Errorf("expected: %q, got: %q", expected, output)214 }215}216217func TestActiveHelpForFlag(t *testing.T) {218 rootCmd := &Command{219 Use: "root",220 Run: emptyRun,221 }222 flagname := "flag"223 rootCmd.Flags().String(flagname, "", "A flag")224225 // Test that multiple activeHelp message can be added226 _ = rootCmd.RegisterFlagCompletionFunc(flagname, func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {227 comps := []string{"first"}228 comps = AppendActiveHelp(comps, activeHelpMessage)229 comps = append(comps, "second")230 comps = AppendActiveHelp(comps, activeHelpMessage2)231 return comps, ShellCompDirectiveNoFileComp232 })233234 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--flag", "")235 if err != nil {236 t.Errorf("Unexpected error: %v", err)237 }238239 expected := strings.Join([]string{240 "first",241 fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),242 "second",243 fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage2),244 ":4",245 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")246247 if output != expected {248 t.Errorf("expected: %q, got: %q", expected, output)249 }250}251252func TestConfigActiveHelp(t *testing.T) {253 rootCmd := &Command{254 Use: "root",255 Run: emptyRun,256 }257258 childCmd := &Command{259 Use: "thechild",260 Short: "The child command",261 Run: emptyRun,262 }263 rootCmd.AddCommand(childCmd)264265 activeHelpCfg := "someconfig,anotherconfig"266 // Set the variable that the user would be setting267 os.Setenv(activeHelpEnvVar(rootCmd.Name()), activeHelpCfg)268269 childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {270 receivedActiveHelpCfg := GetActiveHelpConfig(cmd)271 if receivedActiveHelpCfg != activeHelpCfg {272 t.Errorf("expected activeHelpConfig: %q, but got: %q", activeHelpCfg, receivedActiveHelpCfg)273 }274 return nil, ShellCompDirectiveDefault275 }276277 _, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")278 if err != nil {279 t.Errorf("Unexpected error: %v", err)280 }281282 // Test active help config for a flag283 activeHelpCfg = "a config for a flag"284 // Set the variable that the completions scripts will be setting285 os.Setenv(activeHelpEnvVar(rootCmd.Name()), activeHelpCfg)286287 flagname := "flag"288 childCmd.Flags().String(flagname, "", "A flag")289290 // Test that multiple activeHelp message can be added291 _ = childCmd.RegisterFlagCompletionFunc(flagname, func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {292 receivedActiveHelpCfg := GetActiveHelpConfig(cmd)293 if receivedActiveHelpCfg != activeHelpCfg {294 t.Errorf("expected activeHelpConfig: %q, but got: %q", activeHelpCfg, receivedActiveHelpCfg)295 }296 return nil, ShellCompDirectiveDefault297 })298299 _, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "--flag", "")300 if err != nil {301 t.Errorf("Unexpected error: %v", err)302 }303}304305func TestDisableActiveHelp(t *testing.T) {306 rootCmd := &Command{307 Use: "root",308 Run: emptyRun,309 }310311 childCmd := &Command{312 Use: "thechild",313 Short: "The child command",314 Run: emptyRun,315 }316 rootCmd.AddCommand(childCmd)317318 // Test the disabling of activeHelp using the specific program319 // environment variable that the completions scripts will be setting.320 // Make sure the disabling value is "0" by hard-coding it in the tests;321 // this is for backwards-compatibility as programs will be using this value.322 os.Setenv(activeHelpEnvVar(rootCmd.Name()), "0")323324 childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {325 comps := []string{"first"}326 comps = AppendActiveHelp(comps, activeHelpMessage)327 return comps, ShellCompDirectiveDefault328 }329330 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")331 if err != nil {332 t.Errorf("Unexpected error: %v", err)333 }334 os.Unsetenv(activeHelpEnvVar(rootCmd.Name()))335336 // Make sure there is no ActiveHelp in the output337 expected := strings.Join([]string{338 "first",339 ":0",340 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")341342 if output != expected {343 t.Errorf("expected: %q, got: %q", expected, output)344 }345346 // Now test the global disabling of ActiveHelp347 os.Setenv(activeHelpGlobalEnvVar, "0")348 // Set the specific variable, to make sure it is ignored when the global env349 // var is set properly350 os.Setenv(activeHelpEnvVar(rootCmd.Name()), "1")351352 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")353 if err != nil {354 t.Errorf("Unexpected error: %v", err)355 }356357 // Make sure there is no ActiveHelp in the output358 expected = strings.Join([]string{359 "first",360 ":0",361 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")362363 if output != expected {364 t.Errorf("expected: %q, got: %q", expected, output)365 }366367 // Make sure that if the global env variable is set to anything else than368 // the disable value it is ignored369 os.Setenv(activeHelpGlobalEnvVar, "on")370 // Set the specific variable, to make sure it is used (while ignoring the global env var)371 activeHelpCfg := "1"372 os.Setenv(activeHelpEnvVar(rootCmd.Name()), activeHelpCfg)373374 childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {375 receivedActiveHelpCfg := GetActiveHelpConfig(cmd)376 if receivedActiveHelpCfg != activeHelpCfg {377 t.Errorf("expected activeHelpConfig: %q, but got: %q", activeHelpCfg, receivedActiveHelpCfg)378 }379 return nil, ShellCompDirectiveDefault380 }381382 _, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")383 if err != nil {384 t.Errorf("Unexpected error: %v", err)385 }386}
added:active_help.go+49 added
1package cobra23import (4 "fmt"5 "os"6 "strings"7)89const (10 activeHelpMarker = "_activeHelp_ "11 // The below values should not be changed: programs will be using them explicitly12 // in their user documentation, and users will be using them explicitly.13 activeHelpEnvVarSuffix = "_ACTIVE_HELP"14 activeHelpGlobalEnvVar = "COBRA_ACTIVE_HELP"15 activeHelpGlobalDisable = "0"16)1718// AppendActiveHelp adds the specified string to the specified array to be used as ActiveHelp.19// Such strings will be processed by the completion script and will be shown as ActiveHelp20// to the user.21// The array parameter should be the array that will contain the completions.22// This function can be called multiple times before and/or after completions are added to23// the array. Each time this function is called with the same array, the new24// ActiveHelp line will be shown below the previous ones when completion is triggered.25func AppendActiveHelp(compArray []string, activeHelpStr string) []string {26 return append(compArray, fmt.Sprintf("%s%s", activeHelpMarker, activeHelpStr))27}2829// GetActiveHelpConfig returns the value of the ActiveHelp environment variable30// <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of the root command in upper31// case, with all - replaced by _.32// It will always return "0" if the global environment variable COBRA_ACTIVE_HELP33// is set to "0".34func GetActiveHelpConfig(cmd *Command) string {35 activeHelpCfg := os.Getenv(activeHelpGlobalEnvVar)36 if activeHelpCfg != activeHelpGlobalDisable {37 activeHelpCfg = os.Getenv(activeHelpEnvVar(cmd.Root().Name()))38 }39 return activeHelpCfg40}4142// activeHelpEnvVar returns the name of the program-specific ActiveHelp environment43// variable. It has the format <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of the44// root command in upper case, with all - replaced by _.45func activeHelpEnvVar(name string) string {46 // This format should not be changed: users will be using it explicitly.47 activeHelpEnvVar := strings.ToUpper(fmt.Sprintf("%s%s", name, activeHelpEnvVarSuffix))48 return strings.ReplaceAll(activeHelpEnvVar, "-", "_")49}
added:active_help.md+157 added
1# Active Help23Active 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.45For example, 6```7bash-5.1$ helm repo add [tab]8You must choose a name for the repo you are adding.910bash-5.1$ bin/helm package [tab]11Please specify the path to the chart to package1213bash-5.1$ bin/helm package [tab][tab]14bin/ internal/ scripts/ pkg/ testdata/15```1617**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.18## Supported shells1920Active Help is currently only supported for the following shells:21- 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.22- Zsh2324## Adding Active Help messages2526As 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).2728Adding 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.2930### Active Help for nouns3132Adding 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:3334```go35cmd := &cobra.Command{36 Use: "add [NAME] [URL]",37 Short: "add a chart repository",38 Args: require.ExactArgs(2),39 RunE: func(cmd *cobra.Command, args []string) error {40 return addRepo(args)41 },42 ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {43 var comps []string44 if len(args) == 0 {45 comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")46 } else if len(args) == 1 {47 comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding")48 } else {49 comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments")50 }51 return comps, cobra.ShellCompDirectiveNoFileComp52 },53}54```55The 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:56```57bash-5.1$ helm repo add [tab]58You must choose a name for the repo you are adding5960bash-5.1$ helm repo add grafana [tab]61You must specify the URL for the repo you are adding6263bash-5.1$ helm repo add grafana https://grafana.github.io/helm-charts [tab]64This command does not take any more arguments65```66**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.6768### Active Help for flags6970Providing Active Help for flags is done in the same fashion as for nouns, but using the completion function registered for the flag. For example:71```go72_ = cmd.RegisterFlagCompletionFunc("version", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {73 if len(args) != 2 {74 return cobra.AppendActiveHelp(nil, "You must first specify the chart to install before the --version flag can be completed"), cobra.ShellCompDirectiveNoFileComp75 }76 return compVersionFlag(args[1], toComplete)77 })78```79The example above prints an Active Help message when not enough information was given by the user to complete the `--version` flag.80```81bash-5.1$ bin/helm install myrelease --version 2.0.[tab]82You must first specify the chart to install before the --version flag can be completed8384bash-5.1$ bin/helm install myrelease bitnami/solr --version 2.0.[tab][tab]852.0.1 2.0.2 2.0.386```8788## User control of Active Help8990You 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.91Allowing to configure Active Help is entirely optional; you can use Active Help in your program without doing anything about Active Help configuration.9293The way to configure Active Help is to use the program's Active Help environment94variable. That variable is named `<PROGRAM>_ACTIVE_HELP` where `<PROGRAM>` is the name of your 95program in uppercase with any `-` replaced by an `_`. The variable should be set by the user to whatever96Active Help configuration values are supported by the program.9798For example, say `helm` has chosen to support three levels for Active Help: `on`, `off`, `local`. Then a user99would set the desired behavior to `local` by doing `export HELM_ACTIVE_HELP=local` in their shell.100101For simplicity, when in `cmd.ValidArgsFunction(...)` or a flag's completion function, the program should read the102Active Help configuration using the `cobra.GetActiveHelpConfig(cmd)` function and select what Active Help messages103should or should not be added (instead of reading the environment variable directly).104105For example:106```go107ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {108 activeHelpLevel := cobra.GetActiveHelpConfig(cmd)109110 var comps []string111 if len(args) == 0 {112 if activeHelpLevel != "off" {113 comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")114 }115 } else if len(args) == 1 {116 if activeHelpLevel != "off" {117 comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding")118 }119 } else {120 if activeHelpLevel == "local" {121 comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments")122 }123 }124 return comps, cobra.ShellCompDirectiveNoFileComp125},126```127**Note 1**: If the `<PROGRAM>_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.128129**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 `<PROGRAM>_ACTIVE_HELP` is set to.130131**Note 3**: If the user does not set `<PROGRAM>_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. 132## Active Help with Cobra's default completion command133134Cobra provides a default `completion` command for programs that wish to use it.135When using the default `completion` command, Active Help is configurable in the same136fashion as described above using environment variables. You may wish to document this in more137details for your users.138139## Debugging Active Help140141Debugging 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.142143When 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 `<PROGRAM>_ACTIVE_HELP` where any `-` is replaced by an `_`. For example, we can test deactivating some Active Help as shown below:144```145$ HELM_ACTIVE_HELP=1 bin/helm __complete install wordpress bitnami/h<ENTER>146bitnami/haproxy147bitnami/harbor148_activeHelp_ WARNING: cannot re-use a name that is still in use149:0150Completion ended with directive: ShellCompDirectiveDefault151152$ HELM_ACTIVE_HELP=0 bin/helm __complete install wordpress bitnami/h<ENTER>153bitnami/haproxy154bitnami/harbor155:0156Completion ended with directive: ShellCompDirectiveDefault157```
modified:bash_completions_test.go+12 added
259 unmodified lines
260 checkOmit(t, output, `local_nonpersistent_flags+=("-s")`)261 checkOmit(t, output, `local_nonpersistent_flags+=("--bool-flag")`)262 checkOmit(t, output, `local_nonpersistent_flags+=("-b")`)263}264265func TestBashCompletionNoActiveHelp(t *testing.T) {266 c := &Command{Use: "c", Run: emptyRun}267268 buf := new(bytes.Buffer)269 assertNoErr(t, c.GenBashCompletion(buf))270 output := buf.String()271272 // check that active help is being disabled273 activeHelpVar := activeHelpEnvVar(c.Name())274 check(t, output, fmt.Sprintf("%s=0", activeHelpVar))275}
modified:bash_completions.go+3 added-2 removed
71 unmodified lines
7273 # Prepare the command to request completions for the program.74 # Calling ${words[0]} instead of directly %[1]s allows to handle aliases75 args=("${words[@]:1}")76 # Disable ActiveHelp which is not supported for bash completion v176 requestComp="${words[0]} %[2]s ${args[*]}"77 requestComp="%[8]s=0 ${words[0]} %[2]s ${args[*]}"7879 lastParam=${words[$((${#words[@]}-1))]}80 lastChar=${lastParam:$((${#lastParam}-1)):1}81 __%[1]s_debug "${FUNCNAME[0]}: lastParam ${lastParam}, lastChar ${lastChar}"
301 unmodified lines
383}384385`, name, ShellCompNoDescRequestCmd,386 ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,386 ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))387 ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name)))388}389390func writePostscript(buf io.StringWriter, name string) {391 name = strings.ReplaceAll(name, ":", "__")
307 unmodified lines
added:bash_completionsV2_test.go+19 added
1package cobra23import (4 "bytes"5 "fmt"6 "testing"7)89func TestBashCompletionV2WithActiveHelp(t *testing.T) {10 c := &Command{Use: "c", Run: emptyRun}1112 buf := new(bytes.Buffer)13 assertNoErr(t, c.GenBashCompletionV2(buf, true))14 output := buf.String()1516 // check that active help is not being disabled17 activeHelpVar := activeHelpEnvVar(c.Name())18 checkOmit(t, output, fmt.Sprintf("%s=0", activeHelpVar))19}
modified:bash_completionsV2.go+51 added-8 removed
109 unmodified lines
110 fi111 fi112 fi113114 # Separate activeHelp from normal completions115 local completions=()116 local activeHelp=()117 __%[1]s_extract_activeHelp118119 if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then120 # File extension filtering121 local fullFilter filter filteringCmd122118 # Do not use quotes around the $out variable or else newline123 # Do not use quotes around the $completions variable or else newline124 # characters will be kept.120 for filter in ${out}; do125 for filter in ${completions[*]}; do126 fullFilter+="$filter|"127 done128129 filteringCmd="_filedir $fullFilter"
3 unmodified lines
133 # File completion for directories only134135 # Use printf to strip any trailing newline136 local subdir132 subdir=$(printf "%%s" "${out}")137 subdir=$(printf "%%s" "${completions[0]}")138 if [ -n "$subdir" ]; then139 __%[1]s_debug "Listing directories in $subdir"140 pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return141 else
5 unmodified lines
147 fi148149 __%[1]s_handle_special_char "$cur" :150 __%[1]s_handle_special_char "$cur" =151152 # Print the activeHelp statements before we finish153 if [ ${#activeHelp} -ne 0 ]; then154 printf "\n";155 printf "%%s\n" "${activeHelp[@]}"156 printf "\n"157158 # The prompt format is only available from bash 4.4.159 # We test if it is available before using it.160 if (x=${PS1@P}) 2> /dev/null; then161 printf "%%s" "${PS1@P}${COMP_LINE[@]}"162 else163 # Can't print the prompt. Just print the164 # text the user had typed, it is workable enough.165 printf "%%s" "${COMP_LINE[@]}"166 fi167 fi168}169170# Separate activeHelp lines from real completions.171# Fills the $activeHelp and $completions arrays.172__%[1]s_extract_activeHelp() {173 local activeHelpMarker="%[8]s"174 local endIndex=${#activeHelpMarker}175176 while IFS='' read -r comp; do177 if [ "${comp:0:endIndex}" = "$activeHelpMarker" ]; then178 comp=${comp:endIndex}179 __%[1]s_debug "ActiveHelp found: $comp"180 if [ -n "$comp" ]; then181 activeHelp+=("$comp")182 fi183 else184 # Not an activeHelp line but a normal completion185 completions+=("$comp")186 fi187 done < <(printf "%%s\n" "${out}")188}189190__%[1]s_handle_completion_types() {191 __%[1]s_debug "__%[1]s_handle_completion_types: COMP_TYPE is $COMP_TYPE"192193 case $COMP_TYPE in
10 unmodified lines
204 # Only consider the completions that match205 if [[ $comp == "$cur"* ]]; then206 COMPREPLY+=("$comp")207 fi166 done < <(printf "%%s\n" "${out}")208 done < <(printf "%%s\n" "${completions[@]}")209 ;;210211 *)212 # Type: complete (normal completion)
5 unmodified lines
218__%[1]s_handle_standard_completion_case() {219 local tab=$'\t' comp220221 # Short circuit to optimize if we don't have descriptions180 if [[ $out != *$tab* ]]; then181 IFS=$'\n' read -ra COMPREPLY -d '' < <(IFS=$'\n' compgen -W "$out" -- "$cur")222 if [[ ${completions[*]} != *$tab* ]]; then223 IFS=$'\n' read -ra COMPREPLY -d '' < <(compgen -W "${completions[*]}" -- "$cur")224 return 0225 fi226227 local longest=0
8 unmodified lines
236 COMPREPLY+=("$compline")237 if ((${#comp}>longest)); then238 longest=${#comp}239 fi198 done < <(printf "%%s\n" "${out}")240 done < <(printf "%%s\n" "${completions[@]}")241242 # If there is a single completion left, remove the description text243 if [ ${#COMPREPLY[*]} -eq 1 ]; then244 __%[1]s_debug "COMPREPLY[0]: ${COMPREPLY[0]}"
101 unmodified lines
346347# ex: ts=4 sw=4 et filetype=sh348`, name, compCmd,349 ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,308 ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))350 ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs,351 activeHelpMarker))352}353354// GenBashCompletionFileV2 generates Bash completion version 2.355func (c *Command) GenBashCompletionFileV2(filename string, includeDesc bool) error {
14 unmodified lines
modified:completions.go+6 added
176 unmodified lines
177 }178179 noDescriptions := (cmd.CalledAs() == ShellCompNoDescRequestCmd)180 for _, comp := range completions {181 if GetActiveHelpConfig(finalCmd) == activeHelpGlobalDisable {182 // Remove all activeHelp entries in this case183 if strings.HasPrefix(comp, activeHelpMarker) {184 continue185 }186 }187 if noDescriptions {188 // Remove any description that may be included following a tab character.189 comp = strings.Split(comp, "\t")[0]190 }
639 unmodified lines
modified:fish_completions_test.go+13 added
1package cobra23import (4 "bytes"5 "fmt"6 "testing"7)89func TestCompleteNoDesCmdInFishScript(t *testing.T) {
57 unmodified lines
67 // The command name should not have replaced the ':'68 check(t, output, "-c root:colon")69 checkOmit(t, output, "-c root_colon")70}7172func TestFishCompletionNoActiveHelp(t *testing.T) {73 c := &Command{Use: "c", Run: emptyRun}7475 buf := new(bytes.Buffer)76 assertNoErr(t, c.GenFishCompletion(buf, true))77 output := buf.String()7879 // check that active help is being disabled80 activeHelpVar := activeHelpEnvVar(c.Name())81 check(t, output, fmt.Sprintf("%s=0", activeHelpVar))82}
modified:fish_completions.go+3 added-2 removed
36 unmodified lines
3738 __%[1]s_debug "args: $args"39 __%[1]s_debug "last arg: $lastArg"4041 # Disable ActiveHelp which is not supported for fish shell41 set -l requestComp "$args[1] %[3]s $args[2..-1] $lastArg"42 set -l requestComp "%[9]s=0 $args[1] %[3]s $args[2..-1] $lastArg"4344 __%[1]s_debug "Calling $requestComp"45 set -l results (eval $requestComp 2> /dev/null)46
149 unmodified lines
196complete -c %[2]s -n '__%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results'197198`, nameForVar, name, compCmd,199 ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,199 ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))200 ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name)))201}202203// GenFishCompletion generates fish completion file and writes to the passed writer.204func (c *Command) GenFishCompletion(w io.Writer, includeDesc bool) error {
16 unmodified lines
added:power_completions_test.go+19 added
1package cobra23import (4 "bytes"5 "fmt"6 "testing"7)89func TestPwshCompletionNoActiveHelp(t *testing.T) {10 c := &Command{Use: "c", Run: emptyRun}1112 buf := new(bytes.Buffer)13 assertNoErr(t, c.GenPowerShellCompletion(buf))14 output := buf.String()1516 // check that active help is being disabled17 activeHelpVar := activeHelpEnvVar(c.Name())18 check(t, output, fmt.Sprintf("%s=0", activeHelpVar))19}
modified:powershell_completions.go+5 added-2 removed
59 unmodified lines
6061 # Prepare the command to request completions for the program.62 # Split the command at the first space to separate the program and arguments.63 $Program,$Arguments = $Command.Split(" ",2)6465 $RequestComp="$Program %[2]s $Arguments"66 __%[1]s_debug "RequestComp: $RequestComp"6768 # we cannot use $WordToComplete because it
21 unmodified lines
90`+" $RequestComp=\"$RequestComp\" + ' `\"`\"'"+`91 }9293 __%[1]s_debug "Calling $RequestComp"94 # First disable ActiveHelp which is not supported for Powershell95 $env:%[8]s=09697 #call the command store the output in $out and redirect stderr and stdout to null98 # $Out is an array contains each line per element99 Invoke-Expression -OutVariable out "$RequestComp" 2>&1 | Out-Null10097101 # get directive from last line102 [int]$Directive = $Out[-1].TrimStart(':')103 if ($Directive -eq "") {104 # There is no directive specified
139 unmodified lines
244 }245}246`, name, compCmd,247 ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,245 ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))248 ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name)))249}250251func (c *Command) genPowerShellCompletion(w io.Writer, includeDesc bool) error {252 buf := new(bytes.Buffer)
36 unmodified lines
modified:user_guide.md+4 added
658 unmodified lines
659660## Generating shell completions661662Cobra 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).663664## Providing Active Help665666Cobra 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).
added:zsh_completions_test.go+19 added
1package cobra23import (4 "bytes"5 "fmt"6 "testing"7)89func TestZshCompletionWithActiveHelp(t *testing.T) {10 c := &Command{Use: "c", Run: emptyRun}1112 buf := new(bytes.Buffer)13 assertNoErr(t, c.GenZshCompletion(buf))14 output := buf.String()1516 // check that active help is not being disabled17 activeHelpVar := activeHelpEnvVar(c.Name())18 checkOmit(t, output, fmt.Sprintf("%s=0", activeHelpVar))19}
modified:zsh_completions.go+30 added-1 removed
161 unmodified lines
162 __%[1]s_debug "Completion received error. Ignoring completions."163 return164 fi165166 local activeHelpMarker="%[8]s"167 local endIndex=${#activeHelpMarker}168 local startIndex=$((${#activeHelpMarker}+1))169 local hasActiveHelp=0170 while IFS='\n' read -r comp; do171 # Check if this is an activeHelp statement (i.e., prefixed with $activeHelpMarker)172 if [ "${comp[1,$endIndex]}" = "$activeHelpMarker" ];then173 __%[1]s_debug "ActiveHelp found: $comp"174 comp="${comp[$startIndex,-1]}"175 if [ -n "$comp" ]; then176 compadd -x "${comp}"177 __%[1]s_debug "ActiveHelp will need delimiter"178 hasActiveHelp=1179 fi180181 continue182 fi183184 if [ -n "$comp" ]; then185 # If requested, completions are returned with a description.186 # The description is preceded by a TAB character.187 # For zsh's _describe, we need to use a : instead of a TAB.
8 unmodified lines
196 lastComp=$comp197 fi198 done < <(printf "%%s\n" "${out[@]}")199200 # Add a delimiter after the activeHelp statements, but only if:201 # - there are completions following the activeHelp statements, or202 # - file completion will be performed (so there will be choices after the activeHelp)203 if [ $hasActiveHelp -eq 1 ]; then204 if [ ${#completions} -ne 0 ] || [ $((directive & shellCompDirectiveNoFileComp)) -eq 0 ]; then205 __%[1]s_debug "Adding activeHelp delimiter"206 compadd -x "--"207 hasActiveHelp=0208 fi209 fi210211 if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then212 __%[1]s_debug "Activating nospace."213 noSpace="-S ''"214 fi
66 unmodified lines
281 _%[1]s282fi283`, name, compCmd,284 ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,257 ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))285 ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs,286 activeHelpMarker))287}