Add env variable to suppress completion descriptions on create (#1938)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
COBRA_COMPLETION_DESCRIPTIONS=0 or <PROGRAM>_COMPLETION_DESCRIPTIONS=0 can now be used to disable shell completion descriptions.
authored by Ville Skyttä · committed by GitHub · parent 236f3c0 · Browse files · 4 files·+237 added−11 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+237 added−11 removed
- other:+237 added−11 removed
Provenance
- Commit
e63925d- Tree
2531f88- Author
Ville Skyttä <ville.skytta@upcloud.com>- Committer
GitHub <noreply@github.com>- Parent
236f3c0
4 files changed+237 added−11 removed
modified:site/content/completions/_index.md+3 added
391 unmodified lines392 $ source <(helm completion bash --no-descriptions)393 $ helm completion [tab][tab]394 bash fish powershell zsh395 ```396+397+Setting the `<PROGRAM>_COMPLETION_DESCRIPTIONS` environment variable (falling back to `COBRA_COMPLETION_DESCRIPTIONS` if empty or not set) to a [falsey value](https://pkg.go.dev/strconv#ParseBool) achieves the same. `<PROGRAM>` is the name of your program with all non-ASCII-alphanumeric characters replaced by `_`.398+399 ## Bash completions400 401 ### Dependencies402 177 unmodified linesmodified:active_help.go+3 added-10 removed
15 unmodified lines16 17 import (18 "fmt"19 "os"20- "regexp"21- "strings"20 )21 22 const (23 activeHelpMarker = "_activeHelp_ "24 // The below values should not be changed: programs will be using them explicitly25 // in their user documentation, and users will be using them explicitly.28- activeHelpEnvVarSuffix = "_ACTIVE_HELP"29- activeHelpGlobalEnvVar = "COBRA_ACTIVE_HELP"26+ activeHelpEnvVarSuffix = "ACTIVE_HELP"27+ activeHelpGlobalEnvVar = configEnvVarGlobalPrefix + "_" + activeHelpEnvVarSuffix28 activeHelpGlobalDisable = "0"29 )30 33-var activeHelpEnvVarPrefixSubstRegexp = regexp.MustCompile(`[^A-Z0-9_]`)34-31 // AppendActiveHelp adds the specified string to the specified array to be used as ActiveHelp.32 // Such strings will be processed by the completion script and will be shown as ActiveHelp33 // to the user.34 // The array parameter should be the array that will contain the completions.20 unmodified lines55 // activeHelpEnvVar returns the name of the program-specific ActiveHelp environment56 // variable. It has the format <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of the57 // root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`.58 func activeHelpEnvVar(name string) string {63- // This format should not be changed: users will be using it explicitly.64- activeHelpEnvVar := strings.ToUpper(fmt.Sprintf("%s%s", name, activeHelpEnvVarSuffix))65- activeHelpEnvVar = activeHelpEnvVarPrefixSubstRegexp.ReplaceAllString(activeHelpEnvVar, "_")66- return activeHelpEnvVar59+ return configEnvVar(name, activeHelpEnvVarSuffix)60 }modified:completions_test.go+192 added
16 unmodified lines17 import (18 "bytes"19 "context"20 "fmt"21+ "os"22 "strings"23 "sync"24 "testing"25 )3491 unmodified lines3517 }3518 })3519 }3520 }3521+3522+func TestGetEnvConfig(t *testing.T) {3523+ testCases := []struct {3524+ desc string3525+ use string3526+ suffix string3527+ cmdVar string3528+ globalVar string3529+ cmdVal string3530+ globalVal string3531+ expected string3532+ }{3533+ {3534+ desc: "Command envvar overrides global",3535+ use: "root",3536+ suffix: "test",3537+ cmdVar: "ROOT_TEST",3538+ globalVar: "COBRA_TEST",3539+ cmdVal: "cmd",3540+ globalVal: "global",3541+ expected: "cmd",3542+ },3543+ {3544+ desc: "Missing/empty command envvar falls back to global",3545+ use: "root",3546+ suffix: "test",3547+ cmdVar: "ROOT_TEST",3548+ globalVar: "COBRA_TEST",3549+ cmdVal: "",3550+ globalVal: "global",3551+ expected: "global",3552+ },3553+ {3554+ desc: "Missing/empty command and global envvars fall back to empty",3555+ use: "root",3556+ suffix: "test",3557+ cmdVar: "ROOT_TEST",3558+ globalVar: "COBRA_TEST",3559+ cmdVal: "",3560+ globalVal: "",3561+ expected: "",3562+ },3563+ {3564+ desc: "Periods in command use transform to underscores in env var name",3565+ use: "foo.bar",3566+ suffix: "test",3567+ cmdVar: "FOO_BAR_TEST",3568+ globalVar: "COBRA_TEST",3569+ cmdVal: "cmd",3570+ globalVal: "global",3571+ expected: "cmd",3572+ },3573+ {3574+ desc: "Dashes in command use transform to underscores in env var name",3575+ use: "quux-BAZ",3576+ suffix: "test",3577+ cmdVar: "QUUX_BAZ_TEST",3578+ globalVar: "COBRA_TEST",3579+ cmdVal: "cmd",3580+ globalVal: "global",3581+ expected: "cmd",3582+ },3583+ }3584+3585+ for _, tc := range testCases {3586+ t.Run(tc.desc, func(t *testing.T) {3587+ // Could make env handling cleaner with t.Setenv with Go >= 1.173588+ err := os.Setenv(tc.cmdVar, tc.cmdVal)3589+ defer func() {3590+ assertNoErr(t, os.Unsetenv(tc.cmdVar))3591+ }()3592+ assertNoErr(t, err)3593+ err = os.Setenv(tc.globalVar, tc.globalVal)3594+ defer func() {3595+ assertNoErr(t, os.Unsetenv(tc.globalVar))3596+ }()3597+ assertNoErr(t, err)3598+ cmd := &Command{Use: tc.use}3599+ got := getEnvConfig(cmd, tc.suffix)3600+ if got != tc.expected {3601+ t.Errorf("expected: %q, got: %q", tc.expected, got)3602+ }3603+ })3604+ }3605+}3606+3607+func TestDisableDescriptions(t *testing.T) {3608+ rootCmd := &Command{3609+ Use: "root",3610+ Run: emptyRun,3611+ }3612+3613+ childCmd := &Command{3614+ Use: "thechild",3615+ Short: "The child command",3616+ Run: emptyRun,3617+ }3618+ rootCmd.AddCommand(childCmd)3619+3620+ specificDescriptionsEnvVar := configEnvVar(rootCmd.Name(), configEnvVarSuffixDescriptions)3621+ globalDescriptionsEnvVar := configEnvVar(configEnvVarGlobalPrefix, configEnvVarSuffixDescriptions)3622+3623+ const (3624+ descLineWithDescription = "first\tdescription"3625+ descLineWithoutDescription = "first"3626+ )3627+ childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {3628+ comps := []string{descLineWithDescription}3629+ return comps, ShellCompDirectiveDefault3630+ }3631+3632+ testCases := []struct {3633+ desc string3634+ globalEnvValue string3635+ specificEnvValue string3636+ expectedLine string3637+ }{3638+ {3639+ "No env variables set",3640+ "",3641+ "",3642+ descLineWithDescription,3643+ },3644+ {3645+ "Global value false",3646+ "false",3647+ "",3648+ descLineWithoutDescription,3649+ },3650+ {3651+ "Specific value false",3652+ "",3653+ "false",3654+ descLineWithoutDescription,3655+ },3656+ {3657+ "Both values false",3658+ "false",3659+ "false",3660+ descLineWithoutDescription,3661+ },3662+ {3663+ "Both values true",3664+ "true",3665+ "true",3666+ descLineWithDescription,3667+ },3668+ }3669+3670+ for _, tc := range testCases {3671+ t.Run(tc.desc, func(t *testing.T) {3672+ if err := os.Setenv(specificDescriptionsEnvVar, tc.specificEnvValue); err != nil {3673+ t.Errorf("Unexpected error setting %s: %v", specificDescriptionsEnvVar, err)3674+ }3675+ if err := os.Setenv(globalDescriptionsEnvVar, tc.globalEnvValue); err != nil {3676+ t.Errorf("Unexpected error setting %s: %v", globalDescriptionsEnvVar, err)3677+ }3678+3679+ var run = func() {3680+ output, err := executeCommand(rootCmd, ShellCompRequestCmd, "thechild", "")3681+ if err != nil {3682+ t.Errorf("Unexpected error: %v", err)3683+ }3684+3685+ expected := strings.Join([]string{3686+ tc.expectedLine,3687+ ":0",3688+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")3689+ if output != expected {3690+ t.Errorf("expected: %q, got: %q", expected, output)3691+ }3692+ }3693+3694+ run()3695+3696+ // For empty cases, test also unset state3697+ if tc.specificEnvValue == "" {3698+ if err := os.Unsetenv(specificDescriptionsEnvVar); err != nil {3699+ t.Errorf("Unexpected error unsetting %s: %v", specificDescriptionsEnvVar, err)3700+ }3701+ run()3702+ }3703+ if tc.globalEnvValue == "" {3704+ if err := os.Unsetenv(globalDescriptionsEnvVar); err != nil {3705+ t.Errorf("Unexpected error unsetting %s: %v", globalDescriptionsEnvVar, err)3706+ }3707+ run()3708+ }3709+ })3710+ }3711+}modified:completions.go+39 added-1 removed
15 unmodified lines16 17 import (18 "fmt"19 "os"20+ "regexp"21+ "strconv"22 "strings"23 "sync"24 25 "github.com/spf13/pflag"186 unmodified lines212 // 1- There could be some valid completions even though there was an error213 // 2- Even without completions, we need to print the directive214 }215 214- noDescriptions := (cmd.CalledAs() == ShellCompNoDescRequestCmd)216+ noDescriptions := cmd.CalledAs() == ShellCompNoDescRequestCmd217+ if !noDescriptions {218+ if doDescriptions, err := strconv.ParseBool(getEnvConfig(cmd, configEnvVarSuffixDescriptions)); err == nil {219+ noDescriptions = !doDescriptions220+ }221+ }222 noActiveHelp := GetActiveHelpConfig(finalCmd) == activeHelpGlobalDisable223 out := finalCmd.OutOrStdout()224 for _, comp := range completions {225 if noActiveHelp && strings.HasPrefix(comp, activeHelpMarker) {679 unmodified lines905 // CompErrorln prints the specified completion message to stderr with a newline at the end.906 func CompErrorln(msg string) {907 CompError(fmt.Sprintf("%s\n", msg))908 }909+910+// These values should not be changed: users will be using them explicitly.911+const (912+ configEnvVarGlobalPrefix = "COBRA"913+ configEnvVarSuffixDescriptions = "COMPLETION_DESCRIPTIONS"914+)915+916+var configEnvVarPrefixSubstRegexp = regexp.MustCompile(`[^A-Z0-9_]`)917+918+// configEnvVar returns the name of the program-specific configuration environment919+// variable. It has the format <PROGRAM>_<SUFFIX> where <PROGRAM> is the name of the920+// root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`.921+func configEnvVar(name, suffix string) string {922+ // This format should not be changed: users will be using it explicitly.923+ v := strings.ToUpper(fmt.Sprintf("%s_%s", name, suffix))924+ v = configEnvVarPrefixSubstRegexp.ReplaceAllString(v, "_")925+ return v926+}927+928+// getEnvConfig returns the value of the configuration environment variable929+// <PROGRAM>_<SUFFIX> where <PROGRAM> is the name of the root command in upper930+// case, with all non-ASCII-alphanumeric characters replaced by `_`.931+// If the value is empty or not set, the value of the environment variable932+// COBRA_<SUFFIX> is returned instead.933+func getEnvConfig(cmd *Command, suffix string) string {934+ v := os.Getenv(configEnvVar(cmd.Root().Name(), suffix))935+ if v == "" {936+ v = os.Getenv(configEnvVar(configEnvVarGlobalPrefix, suffix))937+ }938+ return v939+}