Skip to content
Myr

Use golangci-lint (#1044)

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

Use golangci-lint. Repair warnings and errors resulting from linting.

authored by Unai Martinez-Corral · committed by GitHub · parent 1d71ff0 · Browse files · 32 files+437 added−525 removed
This commit

State

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

Diff stats

32 files+437 added−525 removed

  • other:+437 added−525 removed

32 files+437 added−525 removed

modified:cobra/cmd/testdata/root.go.golden+5 added-11 removed
15 unmodified lines
16package cmd1718import (19 "fmt"20 "github.com/spf13/cobra"20 "os"21 "github.com/spf13/cobra"2223 homedir "github.com/mitchellh/go-homedir"24 "github.com/spf13/viper"25)
11 unmodified lines
37This application is a tool to generate the needed files38to quickly create a Cobra application.`,39 // Uncomment the following line if your bare application40 // has an action associated with it:41 // Run: func(cmd *cobra.Command, args []string) { },41 // Run: func(cmd *cobra.Command, args []string) { },42}4344// Execute adds all child commands to the root command and sets flags appropriately.45// This is called by main.main(). It only needs to happen once to the rootCmd.46func Execute() {47 if err := rootCmd.Execute(); err != nil {48 fmt.Println(err)49 os.Exit(1)50 }47 cobra.CheckErr(rootCmd.Execute())48}4950func init() {51 cobra.OnInitialize(initConfig)
16 unmodified lines
68 viper.SetConfigFile(cfgFile)69 } else {70 // Find home directory.71 home, err := homedir.Dir()75 if err != nil {76 fmt.Println(err)77 os.Exit(1)78 }72 cobra.CheckErr(err)7374 // Search config in home directory with name ".testproject" (without extension).75 viper.AddConfigPath(home)76 viper.SetConfigName(".testproject")
2 unmodified lines
79 viper.AutomaticEnv() // read in environment variables that match8081 // If a config file is found, read it in.82 if err := viper.ReadInConfig(); err == nil {89 fmt.Println("Using config file:", viper.ConfigFileUsed())83 fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())84 }85}
modified:cobra/cmd/add_test.go+2 added-4 removed
12 unmodified lines
13 Project: getProject(),14 }15 defer os.RemoveAll(command.AbsolutePath)1617 command.Project.Create()18 if err := command.Create(); err != nil {19 t.Fatal(err)20 }17 assertNoErr(t, command.Project.Create())18 assertNoErr(t, command.Create())1920 generatedFile := fmt.Sprintf("%s/cmd/%s.go", command.AbsolutePath, command.CmdName)21 goldenFile := fmt.Sprintf("testdata/%s.go.golden", command.CmdName)22 err := compareFiles(generatedFile, goldenFile)
28 unmodified lines
modified:cobra/cmd/add.go+4 added-9 removed
38 unmodified lines
39Example: cobra add server -> resulting in a new cmd/server.go`,4041 Run: func(cmd *cobra.Command, args []string) {42 if len(args) < 1 {43 er("add needs a name for the command")43 cobra.CheckErr(fmt.Errorf("add needs a name for the command"))44 }4546 wd, err := os.Getwd()47 if err != nil {48 er(err)49 }47 cobra.CheckErr(err)4849 commandName := validateCmdName(args[0])50 command := &Command{51 CmdName: commandName,
4 unmodified lines
56 Copyright: copyrightLine(),57 },58 }5962 err = command.Create()63 if err != nil {64 er(err)65 }60 cobra.CheckErr(command.Create())6162 fmt.Printf("%s created at %s\n", command.CmdName, command.AbsolutePath)63 },64 }
1 unmodified line
6667func init() {68 addCmd.Flags().StringVarP(&packageName, "package", "t", "", "target package name (e.g. github.com/spf13/hugo)")69 addCmd.Flags().StringVarP(&parentName, "parent", "p", "rootCmd", "variable name of parent command for this command")75 addCmd.Flags().MarkDeprecated("package", "this operation has been removed.")70 cobra.CheckErr(addCmd.Flags().MarkDeprecated("package", "this operation has been removed."))71}7273// validateCmdName returns source without any dashes and underscore.74// If there will be dash or underscore, next letter will be uppered.
50 unmodified lines
modified:cobra/cmd/golden_test.go-27 removed
1 unmodified line
23import (4 "bytes"5 "errors"6 "flag"6 "fmt"7 "io/ioutil"8 "os/exec"9)1012var update = flag.Bool("update", false, "update .golden files")1311func init() {12 // Mute commands.13 addCmd.SetOut(new(bytes.Buffer))14 addCmd.SetErr(new(bytes.Buffer))
39 unmodified lines
54 return errors.New(output.String())55 }56 return nil57}6162// checkLackFiles checks if all elements of expected are in got.63func checkLackFiles(expected, got []string) error {64 lacks := make([]string, 0, len(expected))65 for _, ev := range expected {66 if !stringInStringSlice(ev, got) {67 lacks = append(lacks, ev)68 }69 }70 if len(lacks) > 0 {71 return fmt.Errorf("Lack %v file(s): %v", len(lacks), lacks)72 }73 return nil74}7576// stringInStringSlice checks if s is an element of slice.77func stringInStringSlice(s string, slice []string) bool {78 for _, v := range slice {79 if s == v {80 return true81 }82 }83 return false84}
added:cobra/cmd/helpers_test.go+9 added
1package cmd23import "testing"45func assertNoErr(t *testing.T, e error) {6 if e != nil {7 t.Error(e)8 }9}
modified:cobra/cmd/helpers.go+4 added-116 removed
12 unmodified lines
1314package cmd1516import (17 "bytes"18 "fmt"19 "io"17 "os"18 "os/exec"19 "path/filepath"20 "strings"24 "text/template"2122 "github.com/spf13/cobra"23)2425var srcPaths []string26
13 unmodified lines
40 goExecutable = "go"41 }4243 out, err := exec.Command(goExecutable, "env", "GOPATH").Output()46 if err != nil {47 er(err)48 }44 cobra.CheckErr(err)4546 toolchainGoPath := strings.TrimSpace(string(out))47 goPaths = filepath.SplitList(toolchainGoPath)48 if len(goPaths) == 0 {53 er("$GOPATH is not set")49 cobra.CheckErr("$GOPATH is not set")50 }51 }52 srcPaths = make([]string, 0, len(goPaths))53 for _, goPath := range goPaths {54 srcPaths = append(srcPaths, filepath.Join(goPath, "src"))55 }56}6162func er(msg interface{}) {63 fmt.Println("Error:", msg)64 os.Exit(1)65}6667// isEmpty checks if a given path is empty.68// Hidden files in path are ignored.69func isEmpty(path string) bool {70 fi, err := os.Stat(path)71 if err != nil {72 er(err)73 }7475 if !fi.IsDir() {76 return fi.Size() == 077 }7879 f, err := os.Open(path)80 if err != nil {81 er(err)82 }83 defer f.Close()8485 names, err := f.Readdirnames(-1)86 if err != nil && err != io.EOF {87 er(err)88 }8990 for _, name := range names {91 if len(name) > 0 && name[0] != '.' {92 return false93 }94 }95 return true96}9798// exists checks if a file or directory exists.99func exists(path string) bool {100 if path == "" {101 return false102 }103 _, err := os.Stat(path)104 if err == nil {105 return true106 }107 if !os.IsNotExist(err) {108 er(err)109 }110 return false111}112113func executeTemplate(tmplStr string, data interface{}) (string, error) {114 tmpl, err := template.New("").Funcs(template.FuncMap{"comment": commentifyString}).Parse(tmplStr)115 if err != nil {116 return "", err117 }118119 buf := new(bytes.Buffer)120 err = tmpl.Execute(buf, data)121 return buf.String(), err122}123124func writeStringToFile(path string, s string) error {125 return writeToFile(path, strings.NewReader(s))126}127128// writeToFile writes r to file with path only129// if file/directory on given path doesn't exist.130func writeToFile(path string, r io.Reader) error {131 if exists(path) {132 return fmt.Errorf("%v already exists", path)133 }134135 dir := filepath.Dir(path)136 if dir != "" {137 if err := os.MkdirAll(dir, 0777); err != nil {138 return err139 }140 }141142 file, err := os.Create(path)143 if err != nil {144 return err145 }146 defer file.Close()147148 _, err = io.Copy(file, r)149 return err150}151152// commentfyString comments every line of in.153func commentifyString(in string) string {154 var newlines []string155 lines := strings.Split(in, "\n")156 for _, line := range lines {157 if strings.HasPrefix(line, "//") {158 newlines = append(newlines, line)159 } else {160 if line == "" {161 newlines = append(newlines, "//")162 } else {163 newlines = append(newlines, "// "+line)164 }165 }166 }167 return strings.Join(newlines, "\n")168}
modified:cobra/cmd/init_test.go+1 added-1 removed
57 unmodified lines
5859 for _, tt := range tests {60 t.Run(tt.name, func(t *testing.T) {6162 initCmd.Flags().Set("pkg-name", tt.pkgName)62 assertNoErr(t, initCmd.Flags().Set("pkg-name", tt.pkgName))63 viper.Set("useViper", true)64 projectPath, err := initializeProject(tt.args)65 defer func() {66 if projectPath != "" {
28 unmodified lines
modified:cobra/cmd/init.go+2 added-4 removed
37 unmodified lines
3839 Run: func(_ *cobra.Command, args []string) {4041 projectPath, err := initializeProject(args)42 if err != nil {43 er(err)44 }42 cobra.CheckErr(err)43 fmt.Printf("Your Cobra application is ready at\n%s\n", projectPath)44 },45 }46)4748func init() {49 initCmd.Flags().StringVar(&pkgName, "pkg-name", "", "fully qualified pkg name")52 initCmd.MarkFlagRequired("pkg-name")50 cobra.CheckErr(initCmd.MarkFlagRequired("pkg-name"))51}5253func initializeProject(args []string) (string, error) {54 wd, err := os.Getwd()
25 unmodified lines
modified:cobra/cmd/licenses.go+3 added-1 removed
14 unmodified lines
1516package cmd1718import (19 "fmt"20 "strings"21 "time"2223 "github.com/spf13/cobra"24 "github.com/spf13/viper"25)2627// Licenses contains all possible licenses a user can choose from.
65 unmodified lines
93// error will be printed.94func findLicense(name string) License {95 found := matchLicense(name)96 if found == "" {95 er("unknown license: " + name)97 cobra.CheckErr(fmt.Errorf("unknown license: " + name))98 }99 return Licenses[found]100}101
19 unmodified lines
modified:cobra/cmd/project.go+2 added-1 removed
3 unmodified lines
4 "fmt"5 "os"6 "text/template"78 "github.com/spf13/cobra"9 "github.com/spf13/cobra/cobra/tpl"10)1112// Project contains name, license and paths to projects.
36 unmodified lines
49 }5051 // create cmd/root.go52 if _, err = os.Stat(fmt.Sprintf("%s/cmd", p.AbsolutePath)); os.IsNotExist(err) {52 os.Mkdir(fmt.Sprintf("%s/cmd", p.AbsolutePath), 0751)53 cobra.CheckErr(os.Mkdir(fmt.Sprintf("%s/cmd", p.AbsolutePath), 0751))54 }55 rootFile, err := os.Create(fmt.Sprintf("%s/cmd/root.go", p.AbsolutePath))56 if err != nil {57 return err
41 unmodified lines
modified:cobra/cmd/root.go+3 added-5 removed
45 unmodified lines
46 rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")47 rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution")48 rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project")49 rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration")50 viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))51 viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper"))50 cobra.CheckErr(viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")))51 cobra.CheckErr(viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper")))52 viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")53 viper.SetDefault("license", "apache")5455 rootCmd.AddCommand(addCmd)
6 unmodified lines
62 viper.SetConfigFile(cfgFile)63 } else {64 // Find home directory.65 home, err := homedir.Dir()66 if err != nil {67 er(err)68 }66 cobra.CheckErr(err)6768 // Search config in home directory with name ".cobra" (without extension).69 viper.AddConfigPath(home)70 viper.SetConfigName(".cobra")
8 unmodified lines
modified:cobra/tpl/main.go+6 added-13 removed
22 unmodified lines
23package cmd2425import (26 "fmt"27 "github.com/spf13/cobra"27 "os"28 "github.com/spf13/cobra"29{{ if .Viper }}30 homedir "github.com/mitchellh/go-homedir"31 "github.com/spf13/viper"32{{ end -}}31 "github.com/spf13/viper"{{ end }}32)3334{{ if .Viper -}}35var cfgFile string
10 unmodified lines
46This application is a tool to generate the needed files47to quickly create a Cobra application.` + "`" + `,48 // Uncomment the following line if your bare application49 // has an action associated with it:51 // Run: func(cmd *cobra.Command, args []string) { },50 // Run: func(cmd *cobra.Command, args []string) { },51}5253// Execute adds all child commands to the root command and sets flags appropriately.54// This is called by main.main(). It only needs to happen once to the rootCmd.55func Execute() {57 if err := rootCmd.Execute(); err != nil {58 fmt.Println(err)59 os.Exit(1)60 }56 cobra.CheckErr(rootCmd.Execute())57}5859func init() {60{{- if .Viper }}
20 unmodified lines
81 viper.SetConfigFile(cfgFile)82 } else {83 // Find home directory.84 home, err := homedir.Dir()89 if err != nil {90 fmt.Println(err)91 os.Exit(1)92 }85 cobra.CheckErr(err)8687 // Search config in home directory with name ".{{ .AppName }}" (without extension).88 viper.AddConfigPath(home)89 viper.SetConfigName(".{{ .AppName }}")
2 unmodified lines
92 viper.AutomaticEnv() // read in environment variables that match9394 // If a config file is found, read it in.95 if err := viper.ReadInConfig(); err == nil {103 fmt.Println("Using config file:", viper.ConfigFileUsed())96 fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())97 }98}99{{- end }}100`)
45 unmodified lines
modified:doc/man_docs_test.go+7 added-1 removed
11 unmodified lines
1213 "github.com/spf13/cobra"14)1516func assertNoErr(t *testing.T, e error) {17 if e != nil {18 t.Error(e)19 }20}2122func translate(in string) string {23 return strings.Replace(in, "-", "\\-", -1)24}25
112 unmodified lines
138139func TestManPrintFlagsHidesShortDeperecated(t *testing.T) {140 c := &cobra.Command{}141 c.Flags().StringP("foo", "f", "default", "Foo flag")136 c.Flags().MarkShorthandDeprecated("foo", "don't use it no more")142 assertNoErr(t, c.Flags().MarkShorthandDeprecated("foo", "don't use it no more"))143144 buf := new(bytes.Buffer)145 manPrintFlags(buf, c.Flags())146
75 unmodified lines
modified:doc/man_docs.go+14 added-14 removed
137 unmodified lines
138 }139 return nil140}141142func manPreamble(buf *bytes.Buffer, header *GenManHeader, cmd *cobra.Command, dashedName string) {142func manPreamble(buf io.StringWriter, header *GenManHeader, cmd *cobra.Command, dashedName string) {143 description := cmd.Long144 if len(description) == 0 {145 description = cmd.Short146 }147148 buf.WriteString(fmt.Sprintf(`%% "%s" "%s" "%s" "%s" "%s"148 cobra.WriteStringAndCheck(buf, fmt.Sprintf(`%% "%s" "%s" "%s" "%s" "%s"149# NAME150`, header.Title, header.Section, header.date, header.Source, header.Manual))151 buf.WriteString(fmt.Sprintf("%s \\- %s\n\n", dashedName, cmd.Short))152 buf.WriteString("# SYNOPSIS\n")153 buf.WriteString(fmt.Sprintf("**%s**\n\n", cmd.UseLine()))154 buf.WriteString("# DESCRIPTION\n")155 buf.WriteString(description + "\n\n")151 cobra.WriteStringAndCheck(buf, fmt.Sprintf("%s \\- %s\n\n", dashedName, cmd.Short))152 cobra.WriteStringAndCheck(buf, "# SYNOPSIS\n")153 cobra.WriteStringAndCheck(buf, fmt.Sprintf("**%s**\n\n", cmd.UseLine()))154 cobra.WriteStringAndCheck(buf, "# DESCRIPTION\n")155 cobra.WriteStringAndCheck(buf, description+"\n\n")156}157158func manPrintFlags(buf *bytes.Buffer, flags *pflag.FlagSet) {158func manPrintFlags(buf io.StringWriter, flags *pflag.FlagSet) {159 flags.VisitAll(func(flag *pflag.Flag) {160 if len(flag.Deprecated) > 0 || flag.Hidden {161 return162 }
15 unmodified lines
178 if len(flag.NoOptDefVal) > 0 {179 format += "]"180 }181 format += "\n\t%s\n\n"182 buf.WriteString(fmt.Sprintf(format, flag.DefValue, flag.Usage))182 cobra.WriteStringAndCheck(buf, fmt.Sprintf(format, flag.DefValue, flag.Usage))183 })184}185186func manPrintOptions(buf *bytes.Buffer, command *cobra.Command) {186func manPrintOptions(buf io.StringWriter, command *cobra.Command) {187 flags := command.NonInheritedFlags()188 if flags.HasAvailableFlags() {189 buf.WriteString("# OPTIONS\n")189 cobra.WriteStringAndCheck(buf, "# OPTIONS\n")190 manPrintFlags(buf, flags)191 buf.WriteString("\n")191 cobra.WriteStringAndCheck(buf, "\n")192 }193 flags = command.InheritedFlags()194 if flags.HasAvailableFlags() {195 buf.WriteString("# OPTIONS INHERITED FROM PARENT COMMANDS\n")195 cobra.WriteStringAndCheck(buf, "# OPTIONS INHERITED FROM PARENT COMMANDS\n")196 manPrintFlags(buf, flags)197 buf.WriteString("\n")197 cobra.WriteStringAndCheck(buf, "\n")198 }199}200201func genMan(cmd *cobra.Command, header *GenManHeader) []byte {
44 unmodified lines
modified:doc/man_examples_test.go+2 added-2 removed
15 unmodified lines
16 header := &doc.GenManHeader{17 Title: "MINE",18 Section: "3",19 }20 doc.GenManTree(cmd, header, "/tmp")20 cobra.CheckErr(doc.GenManTree(cmd, header, "/tmp"))21}2223func ExampleGenMan() {24 cmd := &cobra.Command{
4 unmodified lines
29 Title: "MINE",30 Section: "3",31 }32 out := new(bytes.Buffer)33 doc.GenMan(cmd, header, out)33 cobra.CheckErr(doc.GenMan(cmd, header, out))34 fmt.Print(out.String())35}
added:.golangci.yml+48 added
1run:2 deadline: 5m34linters:5 disable-all: true6 enable:7 #- bodyclose8 - deadcode9 #- depguard10 #- dogsled11 #- dupl12 - errcheck13 #- exhaustive14 #- funlen15 - gas16 #- gochecknoinits17 - goconst18 #- gocritic19 #- gocyclo20 #- gofmt21 - goimports22 - golint23 #- gomnd24 #- goprintffuncname25 #- gosec26 #- gosimple27 - govet28 - ineffassign29 - interfacer30 #- lll31 - maligned32 - megacheck33 #- misspell34 #- nakedret35 #- noctx36 #- nolintlint37 #- rowserrcheck38 #- scopelint39 #- staticcheck40 - structcheck41 #- stylecheck42 #- typecheck43 - unconvert44 #- unparam45 #- unused46 - varcheck47 #- whitespace48 fast: false
modified:.travis.yml+4 added-5 removed
1language: go23stages:4 - diff4 - test5 - build67go:8 - 1.14.x9 - 1.15.x10 - tip1112env: GO111MODULE=on1314before_install:15 - go get -u github.com/kyoh86/richgo16 - go get -u github.com/mitchellh/gox17 - curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin latest1819matrix:20 allow_failures:21 - go: tip22 include:21 - stage: diff22 go: 1.14.x23 script: make fmt23 - stage: build24 go: 1.14.x25 script: make cobra_generator2628script: 27script:28 - make test
modified:bash_completions_test.go+20 added-19 removed
38 unmodified lines
39 }40}4142func runShellCheck(s string) error {43 excluded := []string{43 cmd := exec.Command("shellcheck", "-s", "bash", "-", "-e",44 "SC2034", // PREFIX appears unused. Verify it or export it.45 }46 cmd := exec.Command("shellcheck", "-s", "bash", "-", "-e", strings.Join(excluded, ","))45 )46 cmd.Stderr = os.Stderr47 cmd.Stdout = os.Stdout4849 stdin, err := cmd.StdinPipe()50 if err != nil {51 return err52 }53 go func() {55 stdin.Write([]byte(s))54 _, err := stdin.Write([]byte(s))55 CheckErr(err)5657 stdin.Close()58 }()5960 return cmd.Run()
13 unmodified lines
74 BashCompletionFunction: bashCompletionFunc,75 Run: emptyRun,76 }77 rootCmd.Flags().IntP("introot", "i", -1, "help message for flag introot")77 rootCmd.MarkFlagRequired("introot")78 assertNoErr(t, rootCmd.MarkFlagRequired("introot"))7980 // Filename.81 rootCmd.Flags().String("filename", "", "Enter a filename")81 rootCmd.MarkFlagFilename("filename", "json", "yaml", "yml")82 assertNoErr(t, rootCmd.MarkFlagFilename("filename", "json", "yaml", "yml"))8384 // Persistent filename.85 rootCmd.PersistentFlags().String("persistent-filename", "", "Enter a filename")85 rootCmd.MarkPersistentFlagFilename("persistent-filename")86 rootCmd.MarkPersistentFlagRequired("persistent-filename")86 assertNoErr(t, rootCmd.MarkPersistentFlagFilename("persistent-filename"))87 assertNoErr(t, rootCmd.MarkPersistentFlagRequired("persistent-filename"))8889 // Filename extensions.90 rootCmd.Flags().String("filename-ext", "", "Enter a filename (extension limited)")90 rootCmd.MarkFlagFilename("filename-ext")91 assertNoErr(t, rootCmd.MarkFlagFilename("filename-ext"))92 rootCmd.Flags().String("custom", "", "Enter a filename (extension limited)")92 rootCmd.MarkFlagCustom("custom", "__complete_custom")93 assertNoErr(t, rootCmd.MarkFlagCustom("custom", "__complete_custom"))9495 // Subdirectories in a given directory.96 rootCmd.Flags().String("theme", "", "theme to use (located in /themes/THEMENAME/)")96 rootCmd.Flags().SetAnnotation("theme", BashCompSubdirsInDir, []string{"themes"})97 assertNoErr(t, rootCmd.Flags().SetAnnotation("theme", BashCompSubdirsInDir, []string{"themes"}))9899 // For two word flags check100 rootCmd.Flags().StringP("two", "t", "", "this is two word flags")101 rootCmd.Flags().BoolP("two-w-default", "T", false, "this is not two word flags")
7 unmodified lines
109 Run: emptyRun,110 }111112 echoCmd.Flags().String("filename", "", "Enter a filename")112 echoCmd.MarkFlagFilename("filename", "json", "yaml", "yml")113 assertNoErr(t, echoCmd.MarkFlagFilename("filename", "json", "yaml", "yml"))114 echoCmd.Flags().String("config", "", "config to use (located in /config/PROFILE/)")114 echoCmd.Flags().SetAnnotation("config", BashCompSubdirsInDir, []string{"config"})115 assertNoErr(t, echoCmd.Flags().SetAnnotation("config", BashCompSubdirsInDir, []string{"config"}))116117 printCmd := &Command{118 Use: "print [string to print]",119 Args: MinimumNArgs(1),
29 unmodified lines
149 echoCmd.AddCommand(timesCmd)150 rootCmd.AddCommand(echoCmd, printCmd, deprecatedCmd, colonCmd)151152 buf := new(bytes.Buffer)152 rootCmd.GenBashCompletion(buf)153 assertNoErr(t, rootCmd.GenBashCompletion(buf))154 output := buf.String()155156 check(t, output, "_root")157 check(t, output, "_root_echo")
58 unmodified lines
216 c := &Command{Use: "c", Run: emptyRun}217218 const flagName = "hiddenFlag"219 c.Flags().Bool(flagName, false, "")219 c.Flags().MarkHidden(flagName)220 assertNoErr(t, c.Flags().MarkHidden(flagName))221222 buf := new(bytes.Buffer)222 c.GenBashCompletion(buf)223 assertNoErr(t, c.GenBashCompletion(buf))224 output := buf.String()225226 if strings.Contains(output, flagName) {227 t.Errorf("Expected completion to not include %q flag: Got %v", flagName, output)
4 unmodified lines
232 c := &Command{Use: "c", Run: emptyRun}233234 const flagName = "deprecated-flag"235 c.Flags().Bool(flagName, false, "")235 c.Flags().MarkDeprecated(flagName, "use --not-deprecated instead")236 assertNoErr(t, c.Flags().MarkDeprecated(flagName, "use --not-deprecated instead"))237238 buf := new(bytes.Buffer)238 c.GenBashCompletion(buf)239 assertNoErr(t, c.GenBashCompletion(buf))240 output := buf.String()241242 if strings.Contains(output, flagName) {243 t.Errorf("expected completion to not include %q flag: Got %v", flagName, output)
6 unmodified lines
250 c.Flags().StringP("string-flag", "s", "", "string flag")251 c.Flags().BoolP("bool-flag", "b", false, "bool flag")252253 buf := new(bytes.Buffer)253 c.GenBashCompletion(buf)254 assertNoErr(t, c.GenBashCompletion(buf))255 output := buf.String()256257 // check that local nonpersistent flag are not set since we have TraverseChildren set to true258 checkOmit(t, output, `local_nonpersistent_flags+=("--string-flag")`)
5 unmodified lines
modified:bash_completions.go+68 added-65 removed
17 unmodified lines
18 BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag"19 BashCompSubdirsInDir = "cobra_annotation_bash_completion_subdirs_in_dir"20)2122func writePreamble(buf *bytes.Buffer, name string) {23 buf.WriteString(fmt.Sprintf("# bash completion for %-36s -*- shell-script -*-\n", name))24 buf.WriteString(fmt.Sprintf(`22func writePreamble(buf io.StringWriter, name string) {23 WriteStringAndCheck(buf, fmt.Sprintf("# bash completion for %-36s -*- shell-script -*-\n", name))24 WriteStringAndCheck(buf, fmt.Sprintf(`25__%[1]s_debug()26{27 if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then28 echo "$*" >> "${BASH_COMP_DEBUG_FILE}"
350 unmodified lines
379 ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,380 ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))381}382383func writePostscript(buf *bytes.Buffer, name string) {383func writePostscript(buf io.StringWriter, name string) {384 name = strings.Replace(name, ":", "__", -1)385 buf.WriteString(fmt.Sprintf("__start_%s()\n", name))386 buf.WriteString(fmt.Sprintf(`{385 WriteStringAndCheck(buf, fmt.Sprintf("__start_%s()\n", name))386 WriteStringAndCheck(buf, fmt.Sprintf(`{387 local cur prev words cword388 declare -A flaghash 2>/dev/null || :389 declare -A aliashash 2>/dev/null || :390 if declare -F _init_completion >/dev/null 2>&1; then
18 unmodified lines
409 __%[1]s_handle_word410}411412`, name))413 buf.WriteString(fmt.Sprintf(`if [[ $(type -t compopt) = "builtin" ]]; then413 WriteStringAndCheck(buf, fmt.Sprintf(`if [[ $(type -t compopt) = "builtin" ]]; then414 complete -o default -F __start_%s %s415else416 complete -o default -o nospace -F __start_%s %s417fi418419`, name, name, name, name))420 buf.WriteString("# ex: ts=4 sw=4 et filetype=sh\n")420 WriteStringAndCheck(buf, "# ex: ts=4 sw=4 et filetype=sh\n")421}422423func writeCommands(buf *bytes.Buffer, cmd *Command) {424 buf.WriteString(" commands=()\n")423func writeCommands(buf io.StringWriter, cmd *Command) {424 WriteStringAndCheck(buf, " commands=()\n")425 for _, c := range cmd.Commands() {426 if !c.IsAvailableCommand() && c != cmd.helpCommand {427 continue428 }429 buf.WriteString(fmt.Sprintf(" commands+=(%q)\n", c.Name()))429 WriteStringAndCheck(buf, fmt.Sprintf(" commands+=(%q)\n", c.Name()))430 writeCmdAliases(buf, c)431 }432 buf.WriteString("\n")432 WriteStringAndCheck(buf, "\n")433}434435func writeFlagHandler(buf *bytes.Buffer, name string, annotations map[string][]string, cmd *Command) {435func writeFlagHandler(buf io.StringWriter, name string, annotations map[string][]string, cmd *Command) {436 for key, value := range annotations {437 switch key {438 case BashCompFilenameExt:439 buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name))439 WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name))440441 var ext string442 if len(value) > 0 {443 ext = fmt.Sprintf("__%s_handle_filename_extension_flag ", cmd.Root().Name()) + strings.Join(value, "|")444 } else {445 ext = "_filedir"446 }447 buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", ext))447 WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", ext))448 case BashCompCustom:449 buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name))449 WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name))450451 if len(value) > 0 {452 handlers := strings.Join(value, "; ")452 buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", handlers))453 WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", handlers))454 } else {454 buf.WriteString(" flags_completion+=(:)\n")455 WriteStringAndCheck(buf, " flags_completion+=(:)\n")456 }457 case BashCompSubdirsInDir:457 buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name))458 WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name))459460 var ext string461 if len(value) == 1 {462 ext = fmt.Sprintf("__%s_handle_subdirs_in_dir_flag ", cmd.Root().Name()) + value[0]463 } else {464 ext = "_filedir -d"465 }465 buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", ext))466 WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", ext))467 }468 }469}470471const cbn = "\")\n"472470func writeShortFlag(buf *bytes.Buffer, flag *pflag.Flag, cmd *Command) {473func writeShortFlag(buf io.StringWriter, flag *pflag.Flag, cmd *Command) {474 name := flag.Shorthand475 format := " "476 if len(flag.NoOptDefVal) == 0 {477 format += "two_word_"478 }476 format += "flags+=(\"-%s\")\n"477 buf.WriteString(fmt.Sprintf(format, name))479 format += "flags+=(\"-%s" + cbn480 WriteStringAndCheck(buf, fmt.Sprintf(format, name))481 writeFlagHandler(buf, "-"+name, flag.Annotations, cmd)482}483481func writeFlag(buf *bytes.Buffer, flag *pflag.Flag, cmd *Command) {484func writeFlag(buf io.StringWriter, flag *pflag.Flag, cmd *Command) {485 name := flag.Name486 format := " flags+=(\"--%s"487 if len(flag.NoOptDefVal) == 0 {488 format += "="489 }487 format += "\")\n"488 buf.WriteString(fmt.Sprintf(format, name))490 format += cbn491 WriteStringAndCheck(buf, fmt.Sprintf(format, name))492 if len(flag.NoOptDefVal) == 0 {490 format = " two_word_flags+=(\"--%s\")\n"491 buf.WriteString(fmt.Sprintf(format, name))493 format = " two_word_flags+=(\"--%s" + cbn494 WriteStringAndCheck(buf, fmt.Sprintf(format, name))495 }496 writeFlagHandler(buf, "--"+name, flag.Annotations, cmd)497}498496func writeLocalNonPersistentFlag(buf *bytes.Buffer, flag *pflag.Flag) {499func writeLocalNonPersistentFlag(buf io.StringWriter, flag *pflag.Flag) {500 name := flag.Name498 format := " local_nonpersistent_flags+=(\"--%[1]s\")\n"501 format := " local_nonpersistent_flags+=(\"--%[1]s" + cbn502 if len(flag.NoOptDefVal) == 0 {500 format += " local_nonpersistent_flags+=(\"--%[1]s=\")\n"503 format += " local_nonpersistent_flags+=(\"--%[1]s=" + cbn504 }502 buf.WriteString(fmt.Sprintf(format, name))505 WriteStringAndCheck(buf, fmt.Sprintf(format, name))506 if len(flag.Shorthand) > 0 {504 buf.WriteString(fmt.Sprintf(" local_nonpersistent_flags+=(\"-%s\")\n", flag.Shorthand))507 WriteStringAndCheck(buf, fmt.Sprintf(" local_nonpersistent_flags+=(\"-%s\")\n", flag.Shorthand))508 }509}510511// Setup annotations for go completions for registered flags
9 unmodified lines
521 flag.Annotations[BashCompCustom] = []string{fmt.Sprintf("__%[1]s_handle_go_custom_completion", cmd.Root().Name())}522 }523}524522func writeFlags(buf *bytes.Buffer, cmd *Command) {525func writeFlags(buf io.StringWriter, cmd *Command) {526 prepareCustomAnnotationsForFlags(cmd)524 buf.WriteString(` flags=()527 WriteStringAndCheck(buf, ` flags=()528 two_word_flags=()529 local_nonpersistent_flags=()530 flags_with_completion=()531 flags_completion=()
23 unmodified lines
555 writeShortFlag(buf, flag, cmd)556 }557 })558556 buf.WriteString("\n")559 WriteStringAndCheck(buf, "\n")560}561559func writeRequiredFlag(buf *bytes.Buffer, cmd *Command) {560 buf.WriteString(" must_have_one_flag=()\n")562func writeRequiredFlag(buf io.StringWriter, cmd *Command) {563 WriteStringAndCheck(buf, " must_have_one_flag=()\n")564 flags := cmd.NonInheritedFlags()565 flags.VisitAll(func(flag *pflag.Flag) {566 if nonCompletableFlag(flag) {567 return
4 unmodified lines
572 format := " must_have_one_flag+=(\"--%s"573 if flag.Value.Type() != "bool" {574 format += "="575 }573 format += "\")\n"574 buf.WriteString(fmt.Sprintf(format, flag.Name))576 format += cbn577 WriteStringAndCheck(buf, fmt.Sprintf(format, flag.Name))578579 if len(flag.Shorthand) > 0 {577 buf.WriteString(fmt.Sprintf(" must_have_one_flag+=(\"-%s\")\n", flag.Shorthand))580 WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_flag+=(\"-%s"+cbn, flag.Shorthand))581 }582 }583 }584 })585}586584func writeRequiredNouns(buf *bytes.Buffer, cmd *Command) {585 buf.WriteString(" must_have_one_noun=()\n")586 sort.Sort(sort.StringSlice(cmd.ValidArgs))587func writeRequiredNouns(buf io.StringWriter, cmd *Command) {588 WriteStringAndCheck(buf, " must_have_one_noun=()\n")589 sort.Strings(cmd.ValidArgs)590 for _, value := range cmd.ValidArgs {591 // Remove any description that may be included following a tab character.592 // Descriptions are not supported by bash completion.593 value = strings.Split(value, "\t")[0]591 buf.WriteString(fmt.Sprintf(" must_have_one_noun+=(%q)\n", value))594 WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_noun+=(%q)\n", value))595 }596 if cmd.ValidArgsFunction != nil {594 buf.WriteString(" has_completion_function=1\n")597 WriteStringAndCheck(buf, " has_completion_function=1\n")598 }599}600598func writeCmdAliases(buf *bytes.Buffer, cmd *Command) {601func writeCmdAliases(buf io.StringWriter, cmd *Command) {602 if len(cmd.Aliases) == 0 {603 return604 }605603 sort.Sort(sort.StringSlice(cmd.Aliases))606 sort.Strings(cmd.Aliases)607605 buf.WriteString(fmt.Sprint(` if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then`, "\n"))608 WriteStringAndCheck(buf, fmt.Sprint(` if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then`, "\n"))609 for _, value := range cmd.Aliases {607 buf.WriteString(fmt.Sprintf(" command_aliases+=(%q)\n", value))608 buf.WriteString(fmt.Sprintf(" aliashash[%q]=%q\n", value, cmd.Name()))610 WriteStringAndCheck(buf, fmt.Sprintf(" command_aliases+=(%q)\n", value))611 WriteStringAndCheck(buf, fmt.Sprintf(" aliashash[%q]=%q\n", value, cmd.Name()))612 }610 buf.WriteString(` fi`)611 buf.WriteString("\n")613 WriteStringAndCheck(buf, ` fi`)614 WriteStringAndCheck(buf, "\n")615}613func writeArgAliases(buf *bytes.Buffer, cmd *Command) {614 buf.WriteString(" noun_aliases=()\n")615 sort.Sort(sort.StringSlice(cmd.ArgAliases))616func writeArgAliases(buf io.StringWriter, cmd *Command) {617 WriteStringAndCheck(buf, " noun_aliases=()\n")618 sort.Strings(cmd.ArgAliases)619 for _, value := range cmd.ArgAliases {617 buf.WriteString(fmt.Sprintf(" noun_aliases+=(%q)\n", value))620 WriteStringAndCheck(buf, fmt.Sprintf(" noun_aliases+=(%q)\n", value))621 }622}623621func gen(buf *bytes.Buffer, cmd *Command) {624func gen(buf io.StringWriter, cmd *Command) {625 for _, c := range cmd.Commands() {626 if !c.IsAvailableCommand() && c != cmd.helpCommand {627 continue628 }
3 unmodified lines
632 commandName = strings.Replace(commandName, " ", "_", -1)633 commandName = strings.Replace(commandName, ":", "__", -1)634635 if cmd.Root() == cmd {633 buf.WriteString(fmt.Sprintf("_%s_root_command()\n{\n", commandName))636 WriteStringAndCheck(buf, fmt.Sprintf("_%s_root_command()\n{\n", commandName))637 } else {635 buf.WriteString(fmt.Sprintf("_%s()\n{\n", commandName))638 WriteStringAndCheck(buf, fmt.Sprintf("_%s()\n{\n", commandName))639 }640638 buf.WriteString(fmt.Sprintf(" last_command=%q\n", commandName))639 buf.WriteString("\n")640 buf.WriteString(" command_aliases=()\n")641 buf.WriteString("\n")641 WriteStringAndCheck(buf, fmt.Sprintf(" last_command=%q\n", commandName))642 WriteStringAndCheck(buf, "\n")643 WriteStringAndCheck(buf, " command_aliases=()\n")644 WriteStringAndCheck(buf, "\n")645646 writeCommands(buf, cmd)647 writeFlags(buf, cmd)648 writeRequiredFlag(buf, cmd)649 writeRequiredNouns(buf, cmd)650 writeArgAliases(buf, cmd)648 buf.WriteString("}\n\n")651 WriteStringAndCheck(buf, "}\n\n")652}653654// GenBashCompletion generates bash completion file and writes to the passed writer.655func (c *Command) GenBashCompletion(w io.Writer) error {
26 unmodified lines
modified:cobra_test.go+6 added
3 unmodified lines
4 "testing"5 "text/template"6)78func assertNoErr(t *testing.T, e error) {9 if e != nil {10 t.Error(e)11 }12}1314func TestAddTemplateFunctions(t *testing.T) {15 AddTemplateFunc("t", func() bool { return true })16 AddTemplateFuncs(template.FuncMap{17 "f": func() bool { return false },
11 unmodified lines
modified:cobra.go+15 added
17 unmodified lines
1819import (20 "fmt"21 "io"22 "os"23 "reflect"24 "strconv"25 "strings"26 "text/template"
178 unmodified lines
205 }206 }207 return false208}209210// CheckErr prints the msg with the prefix 'Error:' and exits with error code 1. If the msg is nil, it does nothing.211func CheckErr(msg interface{}) {212 if msg != nil {213 fmt.Fprintln(os.Stderr, "Error:", msg)214 os.Exit(1)215 }216}217218// WriteStringAndCheck writes a string into a buffer, and checks if the error is not nil.219func WriteStringAndCheck(b io.StringWriter, s string) {220 _, err := b.WriteString(s)221 CheckErr(err)222}
modified:command_test.go+93 added-106 removed
56 unmodified lines
57 t.Errorf("Expected to not contain: \n %v\nGot: %v", expected, got)58 }59}6061const onetwo = "one two"6263func TestSingleCommand(t *testing.T) {64 var rootCmdArgs []string65 rootCmd := &Command{66 Use: "root",
12 unmodified lines
79 t.Errorf("Unexpected error: %v", err)80 }8182 got := strings.Join(rootCmdArgs, " ")81 expected := "one two"82 if got != expected {83 t.Errorf("rootCmdArgs expected: %q, got: %q", expected, got)83 if got != onetwo {84 t.Errorf("rootCmdArgs expected: %q, got: %q", onetwo, got)85 }86}8788func TestChildCommand(t *testing.T) {
15 unmodified lines
104 t.Errorf("Unexpected error: %v", err)105 }106107 got := strings.Join(child1CmdArgs, " ")107 expected := "one two"108 if got != expected {109 t.Errorf("child1CmdArgs expected: %q, got: %q", expected, got)108 if got != onetwo {109 t.Errorf("child1CmdArgs expected: %q, got: %q", onetwo, got)110 }111}112113func TestCallCommandWithoutSubcommands(t *testing.T) {
30 unmodified lines
144 t.Errorf("Unexpected error: %v", err)145 }146147 if c.Name() != "child" {148 t.Errorf(`invalid command returned from ExecuteC: expected "child"', got %q`, c.Name())148 t.Errorf(`invalid command returned from ExecuteC: expected "child"', got: %q`, c.Name())149 }150}151152func TestExecuteContext(t *testing.T) {
89 unmodified lines
242 t.Errorf("Unexpected error: %v", err)243 }244245 got := strings.Join(timesCmdArgs, " ")246 expected := "one two"247 if got != expected {248 t.Errorf("timesCmdArgs expected: %v, got: %v", expected, got)246 if got != onetwo {247 t.Errorf("timesCmdArgs expected: %v, got: %v", onetwo, got)248 }249}250251func TestEnablePrefixMatching(t *testing.T) {
17 unmodified lines
269 t.Errorf("Unexpected error: %v", err)270 }271272 got := strings.Join(aCmdArgs, " ")274 expected := "one two"275 if got != expected {276 t.Errorf("aCmdArgs expected: %q, got: %q", expected, got)273 if got != onetwo {274 t.Errorf("aCmdArgs expected: %q, got: %q", onetwo, got)275 }276277 EnablePrefixMatching = false278}
25 unmodified lines
304 t.Errorf("Unexpected error: %v", err)305 }306307 got := strings.Join(timesCmdArgs, " ")310 expected := "one two"311 if got != expected {312 t.Errorf("timesCmdArgs expected: %v, got: %v", expected, got)308 if got != onetwo {309 t.Errorf("timesCmdArgs expected: %v, got: %v", onetwo, got)310 }311312 EnablePrefixMatching = false313}
20 unmodified lines
334 t.Errorf("Unexpected error: %v", err)335 }336337 got := strings.Join(fooCmdArgs, " ")341 expected := "one two"342 if got != expected {343 t.Errorf("fooCmdArgs expected: %v, got: %v", expected, got)338 if got != onetwo {339 t.Errorf("fooCmdArgs expected: %v, got: %v", onetwo, got)340 }341}342343// TestGrandChildSameName checks the correct behaviour of cobra in cases,
19 unmodified lines
363 t.Errorf("Unexpected error: %v", err)364 }365366 got := strings.Join(fooCmdArgs, " ")371 expected := "one two"372 if got != expected {373 t.Errorf("fooCmdArgs expected: %v, got: %v", expected, got)367 if got != onetwo {368 t.Errorf("fooCmdArgs expected: %v, got: %v", onetwo, got)369 }370}371372func TestFlagLong(t *testing.T) {
27 unmodified lines
400 t.Errorf("Expected stringFlagValue: %q, got %q", "abc", stringFlagValue)401 }402403 got := strings.Join(cArgs, " ")409 expected := "one two"410 if got != expected {411 t.Errorf("Expected arguments: %q, got %q", expected, got)404 if got != onetwo {405 t.Errorf("rootCmdArgs expected: %q, got: %q", onetwo, got)406 }407}408409func TestFlagShort(t *testing.T) {
24 unmodified lines
434 t.Errorf("Expected stringFlagValue: %q, got %q", "abc", stringFlagValue)435 }436437 got := strings.Join(cArgs, " ")444 expected := "one two"445 if got != expected {446 t.Errorf("Expected arguments: %q, got %q", expected, got)438 if got != onetwo {439 t.Errorf("rootCmdArgs expected: %q, got: %q", onetwo, got)440 }441}442443func TestChildFlag(t *testing.T) {
193 unmodified lines
637 t.Errorf("Unexpected error: %v", err)638 }639640 got := strings.Join(rootCmdArgs, " ")648 expected := "one two"649 if got != expected {650 t.Errorf("rootCmdArgs expected: %q, got %q", expected, got)641 if got != onetwo {642 t.Errorf("rootCmdArgs expected: %q, got %q", onetwo, got)643 }644 if flagValue != 7 {645 t.Errorf("flagValue expected: %v, got %v", 7, flagValue)646 }
75 unmodified lines
722 t.Errorf("Unexpected error: %v", err)723 }724725 got := strings.Join(childCmdArgs, " ")734 expected := "one two"735 if got != expected {736 t.Errorf("childCmdArgs expected: %q, got %q", expected, got)726 if got != onetwo {727 t.Errorf("rootCmdArgs expected: %q, got: %q", onetwo, got)728 }729 if parentFlagValue != 8 {730 t.Errorf("parentFlagValue expected: %v, got %v", 8, parentFlagValue)731 }
4 unmodified lines
736737func TestRequiredFlags(t *testing.T) {738 c := &Command{Use: "c", Run: emptyRun}739 c.Flags().String("foo1", "", "")749 c.MarkFlagRequired("foo1")740 assertNoErr(t, c.MarkFlagRequired("foo1"))741 c.Flags().String("foo2", "", "")751 c.MarkFlagRequired("foo2")742 assertNoErr(t, c.MarkFlagRequired("foo2"))743 c.Flags().String("bar", "", "")744745 expected := fmt.Sprintf("required flag(s) %q, %q not set", "foo1", "foo2")746
7 unmodified lines
754755func TestPersistentRequiredFlags(t *testing.T) {756 parent := &Command{Use: "parent", Run: emptyRun}757 parent.PersistentFlags().String("foo1", "", "")767 parent.MarkPersistentFlagRequired("foo1")758 assertNoErr(t, parent.MarkPersistentFlagRequired("foo1"))759 parent.PersistentFlags().String("foo2", "", "")769 parent.MarkPersistentFlagRequired("foo2")760 assertNoErr(t, parent.MarkPersistentFlagRequired("foo2"))761 parent.Flags().String("foo3", "", "")762763 child := &Command{Use: "child", Run: emptyRun}764 child.Flags().String("bar1", "", "")774 child.MarkFlagRequired("bar1")765 assertNoErr(t, child.MarkFlagRequired("bar1"))766 child.Flags().String("bar2", "", "")776 child.MarkFlagRequired("bar2")767 assertNoErr(t, child.MarkFlagRequired("bar2"))768 child.Flags().String("bar3", "", "")769770 parent.AddCommand(child)771
11 unmodified lines
783784 parent := &Command{Use: "parent", Run: emptyRun}785 parent.PersistentFlags().Bool("foo", false, "")786 flag := parent.PersistentFlags().Lookup("foo")796 parent.MarkPersistentFlagRequired("foo")787 assertNoErr(t, parent.MarkPersistentFlagRequired("foo"))788789 child := &Command{Use: "child", Run: emptyRun}790 child.DisableFlagParsing = true791
497 unmodified lines
1289 if err != nil {1290 t.Errorf("Unexpected error: %v", err)1291 }12921302 if persPreArgs != "one two" {1303 t.Errorf("Expected persPreArgs %q, got %q", "one two", persPreArgs)1293 for _, v := range []struct {1294 name string1295 got string1296 }{1297 {"persPreArgs", persPreArgs},1298 {"preArgs", preArgs},1299 {"runArgs", runArgs},1300 {"postArgs", postArgs},1301 {"persPostArgs", persPostArgs},1302 } {1303 if v.got != onetwo {1304 t.Errorf("Expected %s %q, got %q", v.name, onetwo, v.got)1305 }1306 }1305 if preArgs != "one two" {1306 t.Errorf("Expected preArgs %q, got %q", "one two", preArgs)1307 }1308 if runArgs != "one two" {1309 t.Errorf("Expected runArgs %q, got %q", "one two", runArgs)1310 }1311 if postArgs != "one two" {1312 t.Errorf("Expected postArgs %q, got %q", "one two", postArgs)1313 }1314 if persPostArgs != "one two" {1315 t.Errorf("Expected persPostArgs %q, got %q", "one two", persPostArgs)1316 }1307}13081309func TestPersistentHooks(t *testing.T) {1310 var (
58 unmodified lines
1369 if err != nil {1370 t.Errorf("Unexpected error: %v", err)1371 }13721373 for _, v := range []struct {1374 name string1375 got string1376 }{1383 // TODO: currently PersistenPreRun* defined in parent does not1384 // run if the matchin child subcommand has PersistenPreRun.1385 // If the behavior changes (https://github.com/spf13/cobra/issues/252)1386 // this test must be fixed.1387 if parentPersPreArgs != "" {1388 t.Errorf("Expected blank parentPersPreArgs, got %q", parentPersPreArgs)1377 // TODO: currently PersistenPreRun* defined in parent does not1378 // run if the matchin child subcommand has PersistenPreRun.1379 // If the behavior changes (https://github.com/spf13/cobra/issues/252)1380 // this test must be fixed.1381 {"parentPersPreArgs", parentPersPreArgs},1382 {"parentPreArgs", parentPreArgs},1383 {"parentRunArgs", parentRunArgs},1384 {"parentPostArgs", parentPostArgs},1385 // TODO: currently PersistenPostRun* defined in parent does not1386 // run if the matchin child subcommand has PersistenPostRun.1387 // If the behavior changes (https://github.com/spf13/cobra/issues/252)1388 // this test must be fixed.1389 {"parentPersPostArgs", parentPersPostArgs},1390 } {1391 if v.got != "" {1392 t.Errorf("Expected blank %s, got %q", v.name, v.got)1393 }1394 }1390 if parentPreArgs != "" {1391 t.Errorf("Expected blank parentPreArgs, got %q", parentPreArgs)1392 }1393 if parentRunArgs != "" {1394 t.Errorf("Expected blank parentRunArgs, got %q", parentRunArgs)1395 }1396 if parentPostArgs != "" {1397 t.Errorf("Expected blank parentPostArgs, got %q", parentPostArgs)1398 }1399 // TODO: currently PersistenPostRun* defined in parent does not1400 // run if the matchin child subcommand has PersistenPostRun.1401 // If the behavior changes (https://github.com/spf13/cobra/issues/252)1402 // this test must be fixed.1403 if parentPersPostArgs != "" {1404 t.Errorf("Expected blank parentPersPostArgs, got %q", parentPersPostArgs)1405 }13951407 if childPersPreArgs != "one two" {1408 t.Errorf("Expected childPersPreArgs %q, got %q", "one two", childPersPreArgs)1396 for _, v := range []struct {1397 name string1398 got string1399 }{1400 {"childPersPreArgs", childPersPreArgs},1401 {"childPreArgs", childPreArgs},1402 {"childRunArgs", childRunArgs},1403 {"childPostArgs", childPostArgs},1404 {"childPersPostArgs", childPersPostArgs},1405 } {1406 if v.got != onetwo {1407 t.Errorf("Expected %s %q, got %q", v.name, onetwo, v.got)1408 }1409 }1410 if childPreArgs != "one two" {1411 t.Errorf("Expected childPreArgs %q, got %q", "one two", childPreArgs)1412 }1413 if childRunArgs != "one two" {1414 t.Errorf("Expected childRunArgs %q, got %q", "one two", childRunArgs)1415 }1416 if childPostArgs != "one two" {1417 t.Errorf("Expected childPostArgs %q, got %q", "one two", childPostArgs)1418 }1419 if childPersPostArgs != "one two" {1420 t.Errorf("Expected childPersPostArgs %q, got %q", "one two", childPersPostArgs)1421 }1410}14111412// Related to https://github.com/spf13/cobra/issues/521.1413func TestGlobalNormFuncPropagation(t *testing.T) {
314 unmodified lines
1728// Related to https://github.com/spf13/cobra/issues/463.1729func TestUseDeprecatedFlags(t *testing.T) {1730 c := &Command{Use: "c", Run: emptyRun}1731 c.Flags().BoolP("deprecated", "d", false, "deprecated flag")1744 c.Flags().MarkDeprecated("deprecated", "This flag is deprecated")1732 assertNoErr(t, c.Flags().MarkDeprecated("deprecated", "This flag is deprecated"))17331734 output, err := executeCommand(c, "c", "-d")1735 if err != nil {1736 t.Error("Unexpected error:", err)
118 unmodified lines
1855 args []string1856 call string1857 want string1858 epm bool1871 tc bool1859}18601861func (tc *calledAsTestcase) test(t *testing.T) {1862 defer func(ov bool) { EnablePrefixMatching = ov }(EnablePrefixMatching)
13 unmodified lines
1876 output := new(bytes.Buffer)1877 parent.SetOut(output)1878 parent.SetErr(output)18791893 parent.Execute()1880 _ = parent.Execute()18811882 if called == nil {1883 if tc.call != "" {1884 t.Errorf("missing expected call to command: %s", tc.call)
9 unmodified lines
1894}18951896func TestCalledAs(t *testing.T) {1897 tests := map[string]calledAsTestcase{1911 "find/no-args": {nil, "parent", "parent", false, false},1912 "find/real-name": {[]string{"child1"}, "child1", "child1", false, false},1913 "find/full-alias": {[]string{"that"}, "child2", "that", false, false},1914 "find/part-no-prefix": {[]string{"thi"}, "", "", false, false},1915 "find/part-alias": {[]string{"thi"}, "child1", "this", true, false},1916 "find/conflict": {[]string{"th"}, "", "", true, false},1917 "traverse/no-args": {nil, "parent", "parent", false, true},1918 "traverse/real-name": {[]string{"child1"}, "child1", "child1", false, true},1919 "traverse/full-alias": {[]string{"that"}, "child2", "that", false, true},1920 "traverse/part-no-prefix": {[]string{"thi"}, "", "", false, true},1921 "traverse/part-alias": {[]string{"thi"}, "child1", "this", true, true},1922 "traverse/conflict": {[]string{"th"}, "", "", true, true},1898 "find/no-args": {nil, "parent", "parent", false},1899 "find/real-name": {[]string{"child1"}, "child1", "child1", false},1900 "find/full-alias": {[]string{"that"}, "child2", "that", false},1901 "find/part-no-prefix": {[]string{"thi"}, "", "", false},1902 "find/part-alias": {[]string{"thi"}, "child1", "this", true},1903 "find/conflict": {[]string{"th"}, "", "", true},1904 "traverse/no-args": {nil, "parent", "parent", false},1905 "traverse/real-name": {[]string{"child1"}, "child1", "child1", false},1906 "traverse/full-alias": {[]string{"that"}, "child2", "that", false},1907 "traverse/part-no-prefix": {[]string{"thi"}, "", "", false},1908 "traverse/part-alias": {[]string{"thi"}, "child1", "this", true},1909 "traverse/conflict": {[]string{"th"}, "", "", true},1910 }19111912 for name, tc := range tests {1913 t.Run(name, tc.test)
107 unmodified lines
modified:command.go+57 added-55 removed
82 unmodified lines
8384 // Deprecated defines, if this command is deprecated and should print this string when used.85 Deprecated string8687 // Hidden defines, if this command is hidden and should NOT show up in the list of available commands.88 Hidden bool8987 // Annotations are key/value pairs that can be used by applications to identify or88 // group commands.89 Annotations map[string]string90
31 unmodified lines
122 PersistentPostRun func(cmd *Command, args []string)123 // PersistentPostRunE: PersistentPostRun but returns an error.124 PersistentPostRunE func(cmd *Command, args []string) error125129 // SilenceErrors is an option to quiet errors down stream.130 SilenceErrors bool131132 // SilenceUsage is an option to silence usage when an error occurs.133 SilenceUsage bool134135 // DisableFlagParsing disables the flag parsing.136 // If this is true all flags will be passed to the command as arguments.137 DisableFlagParsing bool138139 // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")140 // will be printed by generating docs for this command.141 DisableAutoGenTag bool142143 // DisableFlagsInUseLine will disable the addition of [flags] to the usage144 // line of a command when printing help or generating docs145 DisableFlagsInUseLine bool146147 // DisableSuggestions disables the suggestions based on Levenshtein distance148 // that go along with 'unknown command' messages.149 DisableSuggestions bool150 // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.151 // Must be > 0.152 SuggestionsMinimumDistance int153154 // TraverseChildren parses flags on all parents before executing child command.155 TraverseChildren bool156157 // FParseErrWhitelist flag parse errors to be ignored158 FParseErrWhitelist FParseErrWhitelist159160 ctx context.Context161162 // commands is the list of commands supported by this program.163 commands []*Command164 // parent is a parent command for this command.165 parent *Command166 // Max lengths of commands' string lengths for use in padding.167 commandsMaxUseLen int168 commandsMaxCommandPathLen int169 commandsMaxNameLen int170 // commandsAreSorted defines, if command slice are sorted or not.171 commandsAreSorted bool172 // commandCalledAs is the name or alias value used to call this command.173 commandCalledAs struct {174 name string175 called bool176 }177126 // args is actual args parsed from flags.127 args []string128 // flagErrorBuf contains all error messages from pflag.129 flagErrorBuf *bytes.Buffer
33 unmodified lines
163 // outWriter is a writer defined by the user that replaces stdout164 outWriter io.Writer165 // errWriter is a writer defined by the user that replaces stderr166 errWriter io.Writer167168 //FParseErrWhitelist flag parse errors to be ignored169 FParseErrWhitelist FParseErrWhitelist170171 // commandsAreSorted defines, if command slice are sorted or not.172 commandsAreSorted bool173 // commandCalledAs is the name or alias value used to call this command.174 commandCalledAs struct {175 name string176 called bool177 }178179 ctx context.Context180181 // commands is the list of commands supported by this program.182 commands []*Command183 // parent is a parent command for this command.184 parent *Command185 // Max lengths of commands' string lengths for use in padding.186 commandsMaxUseLen int187 commandsMaxCommandPathLen int188 commandsMaxNameLen int189190 // TraverseChildren parses flags on all parents before executing child command.191 TraverseChildren bool192193 // Hidden defines, if this command is hidden and should NOT show up in the list of available commands.194 Hidden bool195196 // SilenceErrors is an option to quiet errors down stream.197 SilenceErrors bool198199 // SilenceUsage is an option to silence usage when an error occurs.200 SilenceUsage bool201202 // DisableFlagParsing disables the flag parsing.203 // If this is true all flags will be passed to the command as arguments.204 DisableFlagParsing bool205206 // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")207 // will be printed by generating docs for this command.208 DisableAutoGenTag bool209210 // DisableFlagsInUseLine will disable the addition of [flags] to the usage211 // line of a command when printing help or generating docs212 DisableFlagsInUseLine bool213214 // DisableSuggestions disables the suggestions based on Levenshtein distance215 // that go along with 'unknown command' messages.216 DisableSuggestions bool217218 // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.219 // Must be > 0.220 SuggestionsMinimumDistance int221}222223// Context returns underlying command context. If command wasn't224// executed with ExecuteContext Context returns Background context.
194 unmodified lines
419 bb := new(bytes.Buffer)420 c.outWriter = bb421 c.errWriter = bb422421 c.Usage()423 CheckErr(c.Usage())424425 // Setting things back to normal426 c.outWriter = tmpOutput427 c.errWriter = tmpErr
660 unmodified lines
1088 Run: func(c *Command, args []string) {1089 cmd, _, e := c.Root().Find(args)1090 if cmd == nil || e != nil {1091 c.Printf("Unknown help topic %#q\n", args)1090 c.Root().Usage()1092 CheckErr(c.Root().Usage())1093 } else {1094 cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown1093 cmd.Help()1095 CheckErr(cmd.Help())1096 }1097 },1098 }1099 }
567 unmodified lines
modified:custom_completions_test.go+23 added-23 removed
778 unmodified lines
779 }780 rootCmd.AddCommand(childCmd)781782 rootCmd.Flags().IntP("requiredFlag", "r", -1, "required flag")783 rootCmd.MarkFlagRequired("requiredFlag")783 assertNoErr(t, rootCmd.MarkFlagRequired("requiredFlag"))784 requiredFlag := rootCmd.Flags().Lookup("requiredFlag")785786 rootCmd.PersistentFlags().IntP("requiredPersistent", "p", -1, "required persistent")787 rootCmd.MarkPersistentFlagRequired("requiredPersistent")787 assertNoErr(t, rootCmd.MarkPersistentFlagRequired("requiredPersistent"))788 requiredPersistent := rootCmd.PersistentFlags().Lookup("requiredPersistent")789790 rootCmd.Flags().StringP("release", "R", "", "Release name")791792 childCmd.Flags().BoolP("subRequired", "s", false, "sub required flag")793 childCmd.MarkFlagRequired("subRequired")793 assertNoErr(t, childCmd.MarkFlagRequired("subRequired"))794 childCmd.Flags().BoolP("subNotRequired", "n", false, "sub not required flag")795796 // Test that a required flag is suggested even without the - prefix797 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")
165 unmodified lines
963 }964965 // No extensions. Should be ignored.966 rootCmd.Flags().StringP("file", "f", "", "file flag")967 rootCmd.MarkFlagFilename("file")967 assertNoErr(t, rootCmd.MarkFlagFilename("file"))968969 // Single extension970 rootCmd.Flags().StringP("log", "l", "", "log flag")971 rootCmd.MarkFlagFilename("log", "log")971 assertNoErr(t, rootCmd.MarkFlagFilename("log", "log"))972973 // Multiple extensions974 rootCmd.Flags().StringP("yaml", "y", "", "yaml flag")975 rootCmd.MarkFlagFilename("yaml", "yaml", "yml")975 assertNoErr(t, rootCmd.MarkFlagFilename("yaml", "yaml", "yml"))976977 // Directly using annotation978 rootCmd.Flags().StringP("text", "t", "", "text flag")979 rootCmd.Flags().SetAnnotation("text", BashCompFilenameExt, []string{"txt"})979 assertNoErr(t, rootCmd.Flags().SetAnnotation("text", BashCompFilenameExt, []string{"txt"}))980981 // Test that the completion logic returns the proper info for the completion982 // script to handle the file filtering983 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--file", "")
101 unmodified lines
1085 }10861087 // Filter directories1088 rootCmd.Flags().StringP("dir", "d", "", "dir flag")1089 rootCmd.MarkFlagDirname("dir")1089 assertNoErr(t, rootCmd.MarkFlagDirname("dir"))10901091 // Filter directories within a directory1092 rootCmd.Flags().StringP("subdir", "s", "", "subdir")1093 rootCmd.Flags().SetAnnotation("subdir", BashCompSubdirsInDir, []string{"themes"})1093 assertNoErr(t, rootCmd.Flags().SetAnnotation("subdir", BashCompSubdirsInDir, []string{"themes"}))10941095 // Multiple directory specification get ignored1096 rootCmd.Flags().StringP("manydir", "m", "", "manydir")1097 rootCmd.Flags().SetAnnotation("manydir", BashCompSubdirsInDir, []string{"themes", "colors"})1097 assertNoErr(t, rootCmd.Flags().SetAnnotation("manydir", BashCompSubdirsInDir, []string{"themes", "colors"}))10981099 // Test that the completion logic returns the proper info for the completion1100 // script to handle the directory filtering1101 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--dir", "")
327 unmodified lines
1429 }1430 rootCmd.AddCommand(child)14311432 buf := new(bytes.Buffer)1433 rootCmd.GenBashCompletion(buf)1433 assertNoErr(t, rootCmd.GenBashCompletion(buf))1434 output := buf.String()14351436 check(t, output, "has_completion_function=1")1437}
6 unmodified lines
1444 }1445 rootCmd.AddCommand(child)14461447 buf := new(bytes.Buffer)1448 rootCmd.GenBashCompletion(buf)1448 assertNoErr(t, rootCmd.GenBashCompletion(buf))1449 output := buf.String()14501451 checkOmit(t, output, "has_completion_function=1")1452}
7 unmodified lines
1460 }1461 rootCmd.AddCommand(child)14621463 buf := new(bytes.Buffer)1464 rootCmd.GenBashCompletion(buf)1464 assertNoErr(t, rootCmd.GenBashCompletion(buf))1465 output := buf.String()14661467 check(t, output, ShellCompNoDescRequestCmd)1468}
7 unmodified lines
1476 }1477 rootCmd.AddCommand(child)14781479 buf := new(bytes.Buffer)1480 rootCmd.GenZshCompletionNoDesc(buf)1480 assertNoErr(t, rootCmd.GenZshCompletionNoDesc(buf))1481 output := buf.String()14821483 check(t, output, ShellCompNoDescRequestCmd)1484}
7 unmodified lines
1492 }1493 rootCmd.AddCommand(child)14941495 buf := new(bytes.Buffer)1496 rootCmd.GenZshCompletion(buf)1496 assertNoErr(t, rootCmd.GenZshCompletion(buf))1497 output := buf.String()14981499 check(t, output, ShellCompRequestCmd)1500 checkOmit(t, output, ShellCompNoDescRequestCmd)
4 unmodified lines
1505 Use: "root",1506 Run: emptyRun,1507 }1508 rootCmd.Flags().IntP("introot", "i", -1, "help message for flag introot")1509 rootCmd.RegisterFlagCompletionFunc("introot", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1509 assertNoErr(t, rootCmd.RegisterFlagCompletionFunc("introot", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1510 completions := []string{}1511 for _, comp := range []string{"1\tThe first", "2\tThe second", "10\tThe tenth"} {1512 if strings.HasPrefix(comp, toComplete) {1513 completions = append(completions, comp)1514 }1515 }1516 return completions, ShellCompDirectiveDefault1517 })1517 }))1518 rootCmd.Flags().String("filename", "", "Enter a filename")1519 rootCmd.RegisterFlagCompletionFunc("filename", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1519 assertNoErr(t, rootCmd.RegisterFlagCompletionFunc("filename", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1520 completions := []string{}1521 for _, comp := range []string{"file.yaml\tYAML format", "myfile.json\tJSON format", "file.xml\tXML format"} {1522 if strings.HasPrefix(comp, toComplete) {1523 completions = append(completions, comp)1524 }1525 }1526 return completions, ShellCompDirectiveNoSpace | ShellCompDirectiveNoFileComp1527 })1527 }))15281529 // Test completing an empty string1530 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--introot", "")1531 if err != nil {
170 unmodified lines
1702 Use: "root",1703 Run: emptyRun,1704 }1705 rootCmd.Flags().IntP("introot", "i", -1, "help message for flag introot")1706 rootCmd.RegisterFlagCompletionFunc("introot", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1706 assertNoErr(t, rootCmd.RegisterFlagCompletionFunc("introot", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1707 completions := []string{}1708 for _, comp := range []string{"1\tThe first", "2\tThe second", "10\tThe tenth"} {1709 if strings.HasPrefix(comp, toComplete) {1710 completions = append(completions, comp)1711 }1712 }1713 return completions, ShellCompDirectiveDefault1714 })1714 }))1715 rootCmd.Flags().String("filename", "", "Enter a filename")1716 rootCmd.RegisterFlagCompletionFunc("filename", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1716 assertNoErr(t, rootCmd.RegisterFlagCompletionFunc("filename", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1717 completions := []string{}1718 for _, comp := range []string{"file.yaml\tYAML format", "myfile.json\tJSON format", "file.xml\tXML format"} {1719 if strings.HasPrefix(comp, toComplete) {1720 completions = append(completions, comp)1721 }1722 }1723 return completions, ShellCompDirectiveNoSpace | ShellCompDirectiveNoFileComp1724 })1724 }))17251726 // Test completing an empty string1727 output, err := executeCommand(rootCmd, ShellCompRequestCmd, "--introot", "")1728 if err != nil {
232 unmodified lines
modified:custom_completions.go+2 added-2 removed
525 unmodified lines
526 f, err := os.OpenFile(path,527 os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)528 if err == nil {529 defer f.Close()530 f.WriteString(msg)530 WriteStringAndCheck(f, msg)531 }532 }533534 if printToStdErr {535 // Must print to stderr for this not to be read by the completion script.536 fmt.Fprintf(os.Stderr, msg)536 fmt.Fprint(os.Stderr, msg)537 }538}539540// CompDebugln prints the specified string with a newline at the end
17 unmodified lines
modified:fish_completions_test.go+4 added-4 removed
13 unmodified lines
14 }15 rootCmd.AddCommand(child)1617 buf := new(bytes.Buffer)18 rootCmd.GenFishCompletion(buf, false)18 assertNoErr(t, rootCmd.GenFishCompletion(buf, false))19 output := buf.String()2021 check(t, output, ShellCompNoDescRequestCmd)22}
7 unmodified lines
30 }31 rootCmd.AddCommand(child)3233 buf := new(bytes.Buffer)34 rootCmd.GenFishCompletion(buf, true)34 assertNoErr(t, rootCmd.GenFishCompletion(buf, true))35 output := buf.String()3637 check(t, output, ShellCompRequestCmd)38 checkOmit(t, output, ShellCompNoDescRequestCmd)
1 unmodified line
4041func TestProgWithDash(t *testing.T) {42 rootCmd := &Command{Use: "root-dash", Args: NoArgs, Run: emptyRun}43 buf := new(bytes.Buffer)44 rootCmd.GenFishCompletion(buf, false)44 assertNoErr(t, rootCmd.GenFishCompletion(buf, false))45 output := buf.String()4647 // Functions name should have replace the '-'48 check(t, output, "__root_dash_perform_completion")
6 unmodified lines
5556func TestProgWithColon(t *testing.T) {57 rootCmd := &Command{Use: "root:colon", Args: NoArgs, Run: emptyRun}58 buf := new(bytes.Buffer)59 rootCmd.GenFishCompletion(buf, false)59 assertNoErr(t, rootCmd.GenFishCompletion(buf, false))60 output := buf.String()6162 // Functions name should have replace the ':'63 check(t, output, "__root_colon_perform_completion")
6 unmodified lines
modified:fish_completions.go+3 added-3 removed
6 unmodified lines
7 "os"8 "strings"9)1011func genFishComp(buf *bytes.Buffer, name string, includeDesc bool) {11func genFishComp(buf io.StringWriter, name string, includeDesc bool) {12 // Variables should not contain a '-' or ':' character13 nameForVar := name14 nameForVar = strings.Replace(nameForVar, "-", "_", -1)15 nameForVar = strings.Replace(nameForVar, ":", "_", -1)
1 unmodified line
17 compCmd := ShellCompRequestCmd18 if !includeDesc {19 compCmd = ShellCompNoDescRequestCmd20 }21 buf.WriteString(fmt.Sprintf("# fish completion for %-36s -*- shell-script -*-\n", name))22 buf.WriteString(fmt.Sprintf(`21 WriteStringAndCheck(buf, fmt.Sprintf("# fish completion for %-36s -*- shell-script -*-\n", name))22 WriteStringAndCheck(buf, fmt.Sprintf(`23function __%[1]s_debug24 set file "$BASH_COMP_DEBUG_FILE"25 if test -n "$file"26 echo "$argv" >> $file
181 unmodified lines
modified:Makefile+11 added-7 removed
1BIN="./bin"2SRC=$(shell find . -name "*.go")34ifeq (, $(shell which golangci-lint))5$(warning "could not find golangci-lint in $(PATH), run: curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh")6endif78ifeq (, $(shell which richgo))9$(warning "could not find richgo in $(PATH), run: go get github.com/kyoh86/richgo")10endif118.PHONY: fmt vet test cobra_generator install_deps clean12.PHONY: fmt lint test cobra_generator install_deps clean1314default: all1512all: fmt vet test cobra_generator 16all: fmt test cobra_generator1718fmt:19 $(info ******************** checking formatting ********************)20 @test -z $(shell gofmt -l $(SRC)) || (gofmt -d $(SRC); exit 1)2122lint:23 $(info ******************** running lint tools ********************)24 golangci-lint run -v2518test: install_deps vet26test: install_deps lint27 $(info ******************** running tests ********************)28 richgo test -v ./...2930cobra_generator: install_deps
4 unmodified lines
35install_deps:36 $(info ******************** downloading dependencies ********************)37 go get -v ./...3831vet:32 $(info ******************** vetting ********************)33 go vet ./...3439clean:40 rm -rf $(BIN)
modified:powershell_completions.go+13 added-13 removed
8 unmodified lines
9 "io"10 "os"11)1213func genPowerShellComp(buf *bytes.Buffer, name string, includeDesc bool) {13func genPowerShellComp(buf io.StringWriter, name string, includeDesc bool) {14 compCmd := ShellCompRequestCmd15 if !includeDesc {16 compCmd = ShellCompNoDescRequestCmd17 }18 buf.WriteString(fmt.Sprintf(`# powershell completion for %-36[1]s -*- shell-script -*-18 WriteStringAndCheck(buf, fmt.Sprintf(`# powershell completion for %-36[1]s -*- shell-script -*-1920function __%[1]s_debug {21 if ($env:BASH_COMP_DEBUG_FILE) {22 "$args" | Out-File -Append -FilePath "$env:BASH_COMP_DEBUG_FILE"
22 unmodified lines
45 # The user could have moved the cursor backwards on the command-line.46 # We need to trigger completion from the $CursorPosition location, so we need47 # to truncate the command-line ($Command) up to the $CursorPosition location.48 # Make sure the $Command is longer then the $CursorPosition before we truncate.49 # This happens because the $Command does not include the last space. 49 # This happens because the $Command does not include the last space.50 if ($Command.Length -gt $CursorPosition) {51 $Command=$Command.Substring(0,$CursorPosition)52 }53 __%[1]s_debug "Truncated command: $Command"54 5455 $ShellCompDirectiveError=%[3]d56 $ShellCompDirectiveNoSpace=%[4]d57 $ShellCompDirectiveNoFileComp=%[5]d58 $ShellCompDirectiveFilterFileExt=%[6]d
4 unmodified lines
63 $Program,$Arguments = $Command.Split(" ",2)64 $RequestComp="$Program %[2]s $Arguments"65 __%[1]s_debug "RequestComp: $RequestComp"6667 # we cannot use $WordToComplete because it 67 # we cannot use $WordToComplete because it68 # has the wrong values if the cursor was moved69 # so use the last argument70 if ($WordToComplete -ne "" ) {71 $WordToComplete = $Arguments.Split(" ")[-1]
29 unmodified lines
101 # There is no directive specified102 $Directive = 0103 }104 __%[1]s_debug "The completion directive is: $Directive"105 105106 # remove directive (last element) from out107 $Out = $Out | Where-Object { $_ -ne $Out[-1] }108 __%[1]s_debug "The completions are: $Out"109
31 unmodified lines
141 }142143 if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) {144 __%[1]s_debug "ShellCompDirectiveNoFileComp is called"145 145146 if ($Values.Length -eq 0) {147 # Just print an empty string here so the 147 # Just print an empty string here so the148 # shell does not start to complete paths.149 # We cannot use CompletionResult here because 149 # We cannot use CompletionResult here because150 # it does not accept an empty string as argument.151 ""152 return153 }154 }155156 if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or 156 if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or157 (($Directive -band $ShellCompDirectiveFilterDirs) -ne 0 )) {158 __%[1]s_debug "ShellCompDirectiveFilterFileExt ShellCompDirectiveFilterDirs are not supported"159160 # return here to prevent the completion of the extensions
8 unmodified lines
169 if ( $IsEqualFlag ) {170 __%[1]s_debug "Join the equal sign flag back to the completion value"171 $_.Name = $Flag + "=" + $_.Name172 }173 } 173 }174175 # Get the current mode176 $Mode = (Get-PSReadLineKeyHandler | Where-Object {$_.Key -eq "Tab" }).Function177 __%[1]s_debug "Mode: $Mode"
45 unmodified lines
223224 # zsh like225 "MenuComplete" {226 # insert space after value227 # MenuComplete will automatically show the ToolTip of 227 # MenuComplete will automatically show the ToolTip of228 # the highlighted value at the bottom of the suggestions.229 [System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")230 }231232 # TabCompleteNext and in case we get something unknown233 Default {234 # Like MenuComplete but we don't want to add a space here because 234 # Like MenuComplete but we don't want to add a space here because235 # the user need to press space anyway to get the completion.236 # Description will not be shown because thats not possible with TabCompleteNext237 [System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars), "$($comp.Name)", 'ParameterValue', "$($comp.Description)")238 }
47 unmodified lines
modified:README.md+1 added-8 removed
232 unmodified lines
233 rootCmd.AddCommand(addCmd)234 rootCmd.AddCommand(initCmd)235}236237func er(msg interface{}) {238 fmt.Println("Error:", msg)239 os.Exit(1)240}241237func initConfig() {238 if cfgFile != "" {239 // Use config file from the flag.240 viper.SetConfigFile(cfgFile)241 } else {242 // Find home directory.243 home, err := homedir.Dir()249 if err != nil {250 er(err)251 }244 cobra.CheckErr(err)245246 // Search config in home directory with name ".cobra" (without extension).247 viper.AddConfigPath(home)248 viper.SetConfigName(".cobra")
511 unmodified lines
modified:shell_completions.md+3 added-4 removed
97 unmodified lines
98 Short: "Display one or many resources",99 Long: get_long,100 Example: get_example,101 Run: func(cmd *cobra.Command, args []string) {102 err := RunGet(f, out, cmd, args)103 util.CheckErr(err)102 cobra.CheckErr(RunGet(f, out, cmd, args))103 },104 ValidArgs: validArgs,105}106```
23 unmodified lines
130the completion algorithm if entered manually, e.g. in:131132```bash133$ kubectl get rc [tab][tab]135backend frontend database 134backend frontend database135```136137Note that without declaring `rc` as an alias, the completion algorithm would not know to show the list of138replication controllers following `rc`.
113 unmodified lines
252and you'll get something like253254```bash255$ kubectl exec [tab][tab]257-c --container= -p --pod= 256-c --container= -p --pod=257```258259### Specify dynamic flag completion260
223 unmodified lines
modified:zsh_completions.go+2 added-2 removed
68 unmodified lines
69 _, err := buf.WriteTo(w)70 return err71}7273func genZshComp(buf *bytes.Buffer, name string, includeDesc bool) {73func genZshComp(buf io.StringWriter, name string, includeDesc bool) {74 compCmd := ShellCompRequestCmd75 if !includeDesc {76 compCmd = ShellCompNoDescRequestCmd77 }78 buf.WriteString(fmt.Sprintf(`#compdef _%[1]s %[1]s78 WriteStringAndCheck(buf, fmt.Sprintf(`#compdef _%[1]s %[1]s7980# zsh completion for %-36[1]s -*- shell-script -*-8182__%[1]s_debug()
158 unmodified lines