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
Provenance
- Commit
f464d6c- Tree
d7db01c- Author
Marc Khouzam <marc.khouzam@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
7dc8b00
15 files changed+776 added−15 removed
added:active_help_test.go+386 added
1+package cobra2+3+import (4+ "fmt"5+ "os"6+ "strings"7+ "testing"8+)9+10+const (11+ activeHelpMessage = "This is an activeHelp message"12+ activeHelpMessage2 = "This is the rest of the activeHelp message"13+)14+15+func TestActiveHelpAlone(t *testing.T) {16+ rootCmd := &Command{17+ Use: "root",18+ Run: emptyRun,19+ }20+21+ activeHelpFunc := func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {22+ comps := AppendActiveHelp(nil, activeHelpMessage)23+ return comps, ShellCompDirectiveDefault24+ }25+26+ // Test that activeHelp can be added to a root command27+ rootCmd.ValidArgsFunction = activeHelpFunc28+29+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")30+ if err != nil {31+ t.Errorf("Unexpected error: %v", err)32+ }33+34+ expected := strings.Join([]string{35+ fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),36+ ":0",37+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")38+39+ if output != expected {40+ t.Errorf("expected: %q, got: %q", expected, output)41+ }42+43+ rootCmd.ValidArgsFunction = nil44+45+ // 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)52+53+ childCmd.ValidArgsFunction = activeHelpFunc54+55+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")56+ if err != nil {57+ t.Errorf("Unexpected error: %v", err)58+ }59+60+ expected = strings.Join([]string{61+ fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),62+ ":0",63+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")64+65+ if output != expected {66+ t.Errorf("expected: %q, got: %q", expected, output)67+ }68+}69+70+func TestActiveHelpWithComps(t *testing.T) {71+ rootCmd := &Command{72+ Use: "root",73+ Run: emptyRun,74+ }75+76+ childCmd := &Command{77+ Use: "thechild",78+ Short: "The child command",79+ Run: emptyRun,80+ }81+ rootCmd.AddCommand(childCmd)82+83+ // 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+ }89+90+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")91+ if err != nil {92+ t.Errorf("Unexpected error: %v", err)93+ }94+95+ expected := strings.Join([]string{96+ "first",97+ "second",98+ fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),99+ ":0",100+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")101+102+ if output != expected {103+ t.Errorf("expected: %q, got: %q", expected, output)104+ }105+106+ // 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+ }113+114+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")115+ if err != nil {116+ t.Errorf("Unexpected error: %v", err)117+ }118+119+ expected = strings.Join([]string{120+ fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),121+ "first",122+ "second",123+ ":0",124+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")125+126+ if output != expected {127+ t.Errorf("expected: %q, got: %q", expected, output)128+ }129+130+ // 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+ }137+138+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")139+ if err != nil {140+ t.Errorf("Unexpected error: %v", err)141+ }142+143+ expected = strings.Join([]string{144+ "first",145+ fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),146+ "second",147+ ":0",148+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")149+150+ if output != expected {151+ t.Errorf("expected: %q, got: %q", expected, output)152+ }153+}154+155+func TestMultiActiveHelp(t *testing.T) {156+ rootCmd := &Command{157+ Use: "root",158+ Run: emptyRun,159+ }160+161+ childCmd := &Command{162+ Use: "thechild",163+ Short: "The child command",164+ Run: emptyRun,165+ }166+ rootCmd.AddCommand(childCmd)167+168+ // 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+ }174+175+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")176+ if err != nil {177+ t.Errorf("Unexpected error: %v", err)178+ }179+180+ 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")185+186+ if output != expected {187+ t.Errorf("expected: %q, got: %q", expected, output)188+ }189+190+ // 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+ }198+199+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")200+ if err != nil {201+ t.Errorf("Unexpected error: %v", err)202+ }203+204+ 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")211+212+ if output != expected {213+ t.Errorf("expected: %q, got: %q", expected, output)214+ }215+}216+217+func TestActiveHelpForFlag(t *testing.T) {218+ rootCmd := &Command{219+ Use: "root",220+ Run: emptyRun,221+ }222+ flagname := "flag"223+ rootCmd.Flags().String(flagname, "", "A flag")224+225+ // 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+ })233+234+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--flag", "")235+ if err != nil {236+ t.Errorf("Unexpected error: %v", err)237+ }238+239+ 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")246+247+ if output != expected {248+ t.Errorf("expected: %q, got: %q", expected, output)249+ }250+}251+252+func TestConfigActiveHelp(t *testing.T) {253+ rootCmd := &Command{254+ Use: "root",255+ Run: emptyRun,256+ }257+258+ childCmd := &Command{259+ Use: "thechild",260+ Short: "The child command",261+ Run: emptyRun,262+ }263+ rootCmd.AddCommand(childCmd)264+265+ activeHelpCfg := "someconfig,anotherconfig"266+ // Set the variable that the user would be setting267+ os.Setenv(activeHelpEnvVar(rootCmd.Name()), activeHelpCfg)268+269+ 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+ }276+277+ _, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")278+ if err != nil {279+ t.Errorf("Unexpected error: %v", err)280+ }281+282+ // 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)286+287+ flagname := "flag"288+ childCmd.Flags().String(flagname, "", "A flag")289+290+ // 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+ })298+299+ _, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "--flag", "")300+ if err != nil {301+ t.Errorf("Unexpected error: %v", err)302+ }303+}304+305+func TestDisableActiveHelp(t *testing.T) {306+ rootCmd := &Command{307+ Use: "root",308+ Run: emptyRun,309+ }310+311+ childCmd := &Command{312+ Use: "thechild",313+ Short: "The child command",314+ Run: emptyRun,315+ }316+ rootCmd.AddCommand(childCmd)317+318+ // 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")323+324+ childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {325+ comps := []string{"first"}326+ comps = AppendActiveHelp(comps, activeHelpMessage)327+ return comps, ShellCompDirectiveDefault328+ }329+330+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")331+ if err != nil {332+ t.Errorf("Unexpected error: %v", err)333+ }334+ os.Unsetenv(activeHelpEnvVar(rootCmd.Name()))335+336+ // Make sure there is no ActiveHelp in the output337+ expected := strings.Join([]string{338+ "first",339+ ":0",340+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")341+342+ if output != expected {343+ t.Errorf("expected: %q, got: %q", expected, output)344+ }345+346+ // 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")351+352+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")353+ if err != nil {354+ t.Errorf("Unexpected error: %v", err)355+ }356+357+ // Make sure there is no ActiveHelp in the output358+ expected = strings.Join([]string{359+ "first",360+ ":0",361+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")362+363+ if output != expected {364+ t.Errorf("expected: %q, got: %q", expected, output)365+ }366+367+ // 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)373+374+ 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+ }381+382+ _, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")383+ if err != nil {384+ t.Errorf("Unexpected error: %v", err)385+ }386+}added:active_help.go+49 added
1+package cobra2+3+import (4+ "fmt"5+ "os"6+ "strings"7+)8+9+const (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+)17+18+// 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.25+func AppendActiveHelp(compArray []string, activeHelpStr string) []string {26+ return append(compArray, fmt.Sprintf("%s%s", activeHelpMarker, activeHelpStr))27+}28+29+// 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".34+func 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+}41+42+// 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 _.45+func 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 Help2+3+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.4+5+For example, 6+```7+bash-5.1$ helm repo add [tab]8+You must choose a name for the repo you are adding.9+10+bash-5.1$ bin/helm package [tab]11+Please specify the path to the chart to package12+13+bash-5.1$ bin/helm package [tab][tab]14+bin/ internal/ scripts/ pkg/ testdata/15+```16+17+**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 shells19+20+Active 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+- Zsh23+24+## Adding Active Help messages25+26+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).27+28+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.29+30+### Active Help for nouns31+32+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:33+34+```go35+cmd := &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+```55+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:56+```57+bash-5.1$ helm repo add [tab]58+You must choose a name for the repo you are adding59+60+bash-5.1$ helm repo add grafana [tab]61+You must specify the URL for the repo you are adding62+63+bash-5.1$ helm repo add grafana https://grafana.github.io/helm-charts [tab]64+This 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.67+68+### Active Help for flags69+70+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: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+```79+The example above prints an Active Help message when not enough information was given by the user to complete the `--version` flag.80+```81+bash-5.1$ bin/helm install myrelease --version 2.0.[tab]82+You must first specify the chart to install before the --version flag can be completed83+84+bash-5.1$ bin/helm install myrelease bitnami/solr --version 2.0.[tab][tab]85+2.0.1 2.0.2 2.0.386+```87+88+## User control of Active Help89+90+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.91+Allowing to configure Active Help is entirely optional; you can use Active Help in your program without doing anything about Active Help configuration.92+93+The way to configure Active Help is to use the program's Active Help environment94+variable. That variable is named `<PROGRAM>_ACTIVE_HELP` where `<PROGRAM>` is the name of your 95+program in uppercase with any `-` replaced by an `_`. The variable should be set by the user to whatever96+Active Help configuration values are supported by the program.97+98+For example, say `helm` has chosen to support three levels for Active Help: `on`, `off`, `local`. Then a user99+would set the desired behavior to `local` by doing `export HELM_ACTIVE_HELP=local` in their shell.100+101+For simplicity, when in `cmd.ValidArgsFunction(...)` or a flag's completion function, the program should read the102+Active Help configuration using the `cobra.GetActiveHelpConfig(cmd)` function and select what Active Help messages103+should or should not be added (instead of reading the environment variable directly).104+105+For example:106+```go107+ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {108+ activeHelpLevel := cobra.GetActiveHelpConfig(cmd)109+110+ 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.128+129+**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.130+131+**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 command133+134+Cobra provides a default `completion` command for programs that wish to use it.135+When using the default `completion` command, Active Help is configurable in the same136+fashion as described above using environment variables. You may wish to document this in more137+details for your users.138+139+## Debugging Active Help140+141+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.142+143+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 `<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>146+bitnami/haproxy147+bitnami/harbor148+_activeHelp_ WARNING: cannot re-use a name that is still in use149+:0150+Completion ended with directive: ShellCompDirectiveDefault151+152+$ HELM_ACTIVE_HELP=0 bin/helm __complete install wordpress bitnami/h<ENTER>153+bitnami/haproxy154+bitnami/harbor155+:0156+Completion ended with directive: ShellCompDirectiveDefault157+```modified:bash_completions_test.go+12 added
259 unmodified lines260 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 }264+265+func TestBashCompletionNoActiveHelp(t *testing.T) {266+ c := &Command{Use: "c", Run: emptyRun}267+268+ buf := new(bytes.Buffer)269+ assertNoErr(t, c.GenBashCompletion(buf))270+ output := buf.String()271+272+ // 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 lines72 73 # 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[*]}"78 79 lastParam=${words[$((${#words[@]}-1))]}80 lastChar=${lastParam:$((${#lastParam}-1)):1}81 __%[1]s_debug "${FUNCNAME[0]}: lastParam ${lastParam}, lastChar ${lastChar}"301 unmodified lines383 }384 385 `, name, ShellCompNoDescRequestCmd,386 ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,386- ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))387+ ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name)))388 }389 390 func writePostscript(buf io.StringWriter, name string) {391 name = strings.ReplaceAll(name, ":", "__")307 unmodified linesadded:bash_completionsV2_test.go+19 added
1+package cobra2+3+import (4+ "bytes"5+ "fmt"6+ "testing"7+)8+9+func TestBashCompletionV2WithActiveHelp(t *testing.T) {10+ c := &Command{Use: "c", Run: emptyRun}11+12+ buf := new(bytes.Buffer)13+ assertNoErr(t, c.GenBashCompletionV2(buf, true))14+ output := buf.String()15+16+ // 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 lines110 fi111 fi112 fi113 114+ # Separate activeHelp from normal completions115+ local completions=()116+ local activeHelp=()117+ __%[1]s_extract_activeHelp118+119 if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then120 # File extension filtering121 local fullFilter filter filteringCmd122 118- # 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 done128 129 filteringCmd="_filedir $fullFilter"3 unmodified lines133 # File completion for directories only134 135 # 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 else5 unmodified lines147 fi148 149 __%[1]s_handle_special_char "$cur" :150 __%[1]s_handle_special_char "$cur" =151+152+ # Print the activeHelp statements before we finish153+ if [ ${#activeHelp} -ne 0 ]; then154+ printf "\n";155+ printf "%%s\n" "${activeHelp[@]}"156+ printf "\n"157+158+ # 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 }169 170+# 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}175+176+ 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+}189+190 __%[1]s_handle_completion_types() {191 __%[1]s_debug "__%[1]s_handle_completion_types: COMP_TYPE is $COMP_TYPE"192 193 case $COMP_TYPE in10 unmodified lines204 # 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 ;;210 211 *)212 # Type: complete (normal completion)5 unmodified lines218 __%[1]s_handle_standard_completion_case() {219 local tab=$'\t' comp220 221 # 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 fi226 227 local longest=08 unmodified lines236 COMPREPLY+=("$compline")237 if ((${#comp}>longest)); then238 longest=${#comp}239 fi198- done < <(printf "%%s\n" "${out}")240+ done < <(printf "%%s\n" "${completions[@]}")241 242 # 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 lines346 347 # ex: ts=4 sw=4 et filetype=sh348 `, name, compCmd,349 ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,308- ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))350+ ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs,351+ activeHelpMarker))352 }353 354 // GenBashCompletionFileV2 generates Bash completion version 2.355 func (c *Command) GenBashCompletionFileV2(filename string, includeDesc bool) error {14 unmodified linesmodified:completions.go+6 added
176 unmodified lines177 }178 179 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 linesmodified:fish_completions_test.go+13 added
1 package cobra2 3 import (4 "bytes"5+ "fmt"6 "testing"7 )8 9 func TestCompleteNoDesCmdInFishScript(t *testing.T) {57 unmodified lines67 // The command name should not have replaced the ':'68 check(t, output, "-c root:colon")69 checkOmit(t, output, "-c root_colon")70 }71+72+func TestFishCompletionNoActiveHelp(t *testing.T) {73+ c := &Command{Use: "c", Run: emptyRun}74+75+ buf := new(bytes.Buffer)76+ assertNoErr(t, c.GenFishCompletion(buf, true))77+ output := buf.String()78+79+ // 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 lines37 38 __%[1]s_debug "args: $args"39 __%[1]s_debug "last arg: $lastArg"40 41+ # 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"43 44 __%[1]s_debug "Calling $requestComp"45 set -l results (eval $requestComp 2> /dev/null)46 149 unmodified lines196 complete -c %[2]s -n '__%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results'197 198 `, nameForVar, name, compCmd,199 ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,199- ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))200+ ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name)))201 }202 203 // GenFishCompletion generates fish completion file and writes to the passed writer.204 func (c *Command) GenFishCompletion(w io.Writer, includeDesc bool) error {16 unmodified linesadded:power_completions_test.go+19 added
1+package cobra2+3+import (4+ "bytes"5+ "fmt"6+ "testing"7+)8+9+func TestPwshCompletionNoActiveHelp(t *testing.T) {10+ c := &Command{Use: "c", Run: emptyRun}11+12+ buf := new(bytes.Buffer)13+ assertNoErr(t, c.GenPowerShellCompletion(buf))14+ output := buf.String()15+16+ // 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 lines60 61 # 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)64+65 $RequestComp="$Program %[2]s $Arguments"66 __%[1]s_debug "RequestComp: $RequestComp"67 68 # we cannot use $WordToComplete because it21 unmodified lines90 `+" $RequestComp=\"$RequestComp\" + ' `\"`\"'"+`91 }92 93 __%[1]s_debug "Calling $RequestComp"94+ # First disable ActiveHelp which is not supported for Powershell95+ $env:%[8]s=096+97 #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-Null100 97-101 # get directive from last line102 [int]$Directive = $Out[-1].TrimStart(':')103 if ($Directive -eq "") {104 # There is no directive specified139 unmodified lines244 }245 }246 `, name, compCmd,247 ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,245- ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))248+ ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name)))249 }250 251 func (c *Command) genPowerShellCompletion(w io.Writer, includeDesc bool) error {252 buf := new(bytes.Buffer)36 unmodified linesmodified:user_guide.md+4 added
658 unmodified lines659 660 ## Generating shell completions661 662 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).663+664+## Providing Active Help665+666+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).added:zsh_completions_test.go+19 added
1+package cobra2+3+import (4+ "bytes"5+ "fmt"6+ "testing"7+)8+9+func TestZshCompletionWithActiveHelp(t *testing.T) {10+ c := &Command{Use: "c", Run: emptyRun}11+12+ buf := new(bytes.Buffer)13+ assertNoErr(t, c.GenZshCompletion(buf))14+ output := buf.String()15+16+ // 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 lines162 __%[1]s_debug "Completion received error. Ignoring completions."163 return164 fi165 166+ 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+ fi180+181+ continue182+ fi183+184 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 lines196 lastComp=$comp197 fi198 done < <(printf "%%s\n" "${out[@]}")199 200+ # 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+ fi210+211 if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then212 __%[1]s_debug "Activating nospace."213 noSpace="-S ''"214 fi66 unmodified lines281 _%[1]s282 fi283 `, name, compCmd,284 ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,257- ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))285+ ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs,286+ activeHelpMarker))287 }