Skip to content
Myr

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

4 files+237 added−11 removed

modified:site/content/completions/_index.md+3 added
391 unmodified lines
392$ source <(helm completion bash --no-descriptions)393$ helm completion [tab][tab]394bash fish powershell zsh395```396397Setting 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 `_`.398399## Bash completions400401### Dependencies402
177 unmodified lines
modified:active_help.go+3 added-10 removed
15 unmodified lines
1617import (18 "fmt"19 "os"20 "regexp"21 "strings"20)2122const (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)3033var activeHelpEnvVarPrefixSubstRegexp = regexp.MustCompile(`[^A-Z0-9_]`)3431// 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 lines
55// 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 `_`.58func 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 lines
17import (18 "bytes"19 "context"20 "fmt"21 "os"22 "strings"23 "sync"24 "testing"25)
3491 unmodified lines
3517 }3518 })3519 }3520}35213522func 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 }35843585 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}36063607func TestDisableDescriptions(t *testing.T) {3608 rootCmd := &Command{3609 Use: "root",3610 Run: emptyRun,3611 }36123613 childCmd := &Command{3614 Use: "thechild",3615 Short: "The child command",3616 Run: emptyRun,3617 }3618 rootCmd.AddCommand(childCmd)36193620 specificDescriptionsEnvVar := configEnvVar(rootCmd.Name(), configEnvVarSuffixDescriptions)3621 globalDescriptionsEnvVar := configEnvVar(configEnvVarGlobalPrefix, configEnvVarSuffixDescriptions)36223623 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 }36313632 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 }36693670 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 }36783679 var run = func() {3680 output, err := executeCommand(rootCmd, ShellCompRequestCmd, "thechild", "")3681 if err != nil {3682 t.Errorf("Unexpected error: %v", err)3683 }36843685 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 }36933694 run()36953696 // 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 lines
1617import (18 "fmt"19 "os"20 "regexp"21 "strconv"22 "strings"23 "sync"2425 "github.com/spf13/pflag"
186 unmodified lines
212 // 1- There could be some valid completions even though there was an error213 // 2- Even without completions, we need to print the directive214 }215214 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 lines
905// CompErrorln prints the specified completion message to stderr with a newline at the end.906func CompErrorln(msg string) {907 CompError(fmt.Sprintf("%s\n", msg))908}909910// These values should not be changed: users will be using them explicitly.911const (912 configEnvVarGlobalPrefix = "COBRA"913 configEnvVarSuffixDescriptions = "COMPLETION_DESCRIPTIONS"914)915916var configEnvVarPrefixSubstRegexp = regexp.MustCompile(`[^A-Z0-9_]`)917918// 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 `_`.921func 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}927928// 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.933func 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}