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
Provenance
- Commit
652c755- Tree
0305519- Author
Unai Martinez-Corral <38422348+umarcor@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
1d71ff0
32 files changed+437 added−525 removed
modified:cobra/cmd/testdata/root.go.golden+5 added-11 removed
15 unmodified lines16 package cmd17 18 import (19 "fmt"20- "github.com/spf13/cobra"20 "os"21+ "github.com/spf13/cobra"22 23 homedir "github.com/mitchellh/go-homedir"24 "github.com/spf13/viper"25 )11 unmodified lines37 This application is a tool to generate the needed files38 to 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 }43 44 // 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.46 func Execute() {47- if err := rootCmd.Execute(); err != nil {48- fmt.Println(err)49- os.Exit(1)50- }47+ cobra.CheckErr(rootCmd.Execute())48 }49 50 func init() {51 cobra.OnInitialize(initConfig)16 unmodified lines68 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)73 74 // Search config in home directory with name ".testproject" (without extension).75 viper.AddConfigPath(home)76 viper.SetConfigName(".testproject")2 unmodified lines79 viper.AutomaticEnv() // read in environment variables that match80 81 // 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 lines13 Project: getProject(),14 }15 defer os.RemoveAll(command.AbsolutePath)16 17- 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())19 20 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 linesmodified:cobra/cmd/add.go+4 added-9 removed
38 unmodified lines39 Example: cobra add server -> resulting in a new cmd/server.go`,40 41 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 }45 46 wd, err := os.Getwd()47- if err != nil {48- er(err)49- }47+ cobra.CheckErr(err)48 49 commandName := validateCmdName(args[0])50 command := &Command{51 CmdName: commandName,4 unmodified lines56 Copyright: copyrightLine(),57 },58 }59 62- err = command.Create()63- if err != nil {64- er(err)65- }60+ cobra.CheckErr(command.Create())61 62 fmt.Printf("%s created at %s\n", command.CmdName, command.AbsolutePath)63 },64 }1 unmodified line66 67 func 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 }72 73 // validateCmdName returns source without any dashes and underscore.74 // If there will be dash or underscore, next letter will be uppered.50 unmodified linesmodified:cobra/cmd/golden_test.go-27 removed
1 unmodified line2 3 import (4 "bytes"5 "errors"6- "flag"6 "fmt"7 "io/ioutil"8 "os/exec"9 )10 12-var update = flag.Bool("update", false, "update .golden files")13-11 func init() {12 // Mute commands.13 addCmd.SetOut(new(bytes.Buffer))14 addCmd.SetErr(new(bytes.Buffer))39 unmodified lines54 return errors.New(output.String())55 }56 return nil57 }61-62-// checkLackFiles checks if all elements of expected are in got.63-func 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-}75-76-// stringInStringSlice checks if s is an element of slice.77-func 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
1+package cmd2+3+import "testing"4+5+func 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 lines13 14 package cmd15 16 import (17- "bytes"18- "fmt"19- "io"17 "os"18 "os/exec"19 "path/filepath"20 "strings"24- "text/template"21+22+ "github.com/spf13/cobra"23 )24 25 var srcPaths []string26 13 unmodified lines40 goExecutable = "go"41 }42 43 out, err := exec.Command(goExecutable, "env", "GOPATH").Output()46- if err != nil {47- er(err)48- }44+ cobra.CheckErr(err)45 46 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 }61-62-func er(msg interface{}) {63- fmt.Println("Error:", msg)64- os.Exit(1)65-}66-67-// isEmpty checks if a given path is empty.68-// Hidden files in path are ignored.69-func isEmpty(path string) bool {70- fi, err := os.Stat(path)71- if err != nil {72- er(err)73- }74-75- if !fi.IsDir() {76- return fi.Size() == 077- }78-79- f, err := os.Open(path)80- if err != nil {81- er(err)82- }83- defer f.Close()84-85- names, err := f.Readdirnames(-1)86- if err != nil && err != io.EOF {87- er(err)88- }89-90- for _, name := range names {91- if len(name) > 0 && name[0] != '.' {92- return false93- }94- }95- return true96-}97-98-// exists checks if a file or directory exists.99-func 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-}112-113-func 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- }118-119- buf := new(bytes.Buffer)120- err = tmpl.Execute(buf, data)121- return buf.String(), err122-}123-124-func writeStringToFile(path string, s string) error {125- return writeToFile(path, strings.NewReader(s))126-}127-128-// writeToFile writes r to file with path only129-// if file/directory on given path doesn't exist.130-func writeToFile(path string, r io.Reader) error {131- if exists(path) {132- return fmt.Errorf("%v already exists", path)133- }134-135- dir := filepath.Dir(path)136- if dir != "" {137- if err := os.MkdirAll(dir, 0777); err != nil {138- return err139- }140- }141-142- file, err := os.Create(path)143- if err != nil {144- return err145- }146- defer file.Close()147-148- _, err = io.Copy(file, r)149- return err150-}151-152-// commentfyString comments every line of in.153-func 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 lines58 59 for _, tt := range tests {60 t.Run(tt.name, func(t *testing.T) {61 62- 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 linesmodified:cobra/cmd/init.go+2 added-4 removed
37 unmodified lines38 39 Run: func(_ *cobra.Command, args []string) {40 41 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 )47 48 func 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 }52 53 func initializeProject(args []string) (string, error) {54 wd, err := os.Getwd()25 unmodified linesmodified:cobra/cmd/licenses.go+3 added-1 removed
14 unmodified lines15 16 package cmd17 18 import (19+ "fmt"20 "strings"21 "time"22 23+ "github.com/spf13/cobra"24 "github.com/spf13/viper"25 )26 27 // Licenses contains all possible licenses a user can choose from.65 unmodified lines93 // error will be printed.94 func 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 linesmodified:cobra/cmd/project.go+2 added-1 removed
3 unmodified lines4 "fmt"5 "os"6 "text/template"7 8+ "github.com/spf13/cobra"9 "github.com/spf13/cobra/cobra/tpl"10 )11 12 // Project contains name, license and paths to projects.36 unmodified lines49 }50 51 // 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 err41 unmodified linesmodified:cobra/cmd/root.go+3 added-5 removed
45 unmodified lines46 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")54 55 rootCmd.AddCommand(addCmd)6 unmodified lines62 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)67 68 // Search config in home directory with name ".cobra" (without extension).69 viper.AddConfigPath(home)70 viper.SetConfigName(".cobra")8 unmodified linesmodified:cobra/tpl/main.go+6 added-13 removed
22 unmodified lines23 package cmd24 25 import (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 )33 34 {{ if .Viper -}}35 var cfgFile string10 unmodified lines46 This application is a tool to generate the needed files47 to 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 }52 53 // 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.55 func Execute() {57- if err := rootCmd.Execute(); err != nil {58- fmt.Println(err)59- os.Exit(1)60- }56+ cobra.CheckErr(rootCmd.Execute())57 }58 59 func init() {60 {{- if .Viper }}20 unmodified lines81 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)86 87 // Search config in home directory with name ".{{ .AppName }}" (without extension).88 viper.AddConfigPath(home)89 viper.SetConfigName(".{{ .AppName }}")2 unmodified lines92 viper.AutomaticEnv() // read in environment variables that match93 94 // 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 linesmodified:doc/man_docs_test.go+7 added-1 removed
11 unmodified lines12 13 "github.com/spf13/cobra"14 )15 16+func assertNoErr(t *testing.T, e error) {17+ if e != nil {18+ t.Error(e)19+ }20+}21+22 func translate(in string) string {23 return strings.Replace(in, "-", "\\-", -1)24 }25 112 unmodified lines138 139 func 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"))143 144 buf := new(bytes.Buffer)145 manPrintFlags(buf, c.Flags())146 75 unmodified linesmodified:doc/man_docs.go+14 added-14 removed
137 unmodified lines138 }139 return nil140 }141 142-func manPreamble(buf *bytes.Buffer, header *GenManHeader, cmd *cobra.Command, dashedName string) {142+func manPreamble(buf io.StringWriter, header *GenManHeader, cmd *cobra.Command, dashedName string) {143 description := cmd.Long144 if len(description) == 0 {145 description = cmd.Short146 }147 148- 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 }157 158-func manPrintFlags(buf *bytes.Buffer, flags *pflag.FlagSet) {158+func 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 lines178 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 }185 186-func manPrintOptions(buf *bytes.Buffer, command *cobra.Command) {186+func 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 }200 201 func genMan(cmd *cobra.Command, header *GenManHeader) []byte {44 unmodified linesmodified:doc/man_examples_test.go+2 added-2 removed
15 unmodified lines16 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 }22 23 func ExampleGenMan() {24 cmd := &cobra.Command{4 unmodified lines29 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
1+run:2+ deadline: 5m3+4+linters: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: falsemodified:.travis.yml+4 added-5 removed
1 language: go2 3 stages:4- - diff4 - test5 - build6 7 go:8 - 1.14.x9 - 1.15.x10 - tip11 12+env: GO111MODULE=on13+14 before_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 latest18 19 matrix: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_generator26 28-script: 27+script:28 - make testmodified:bash_completions_test.go+20 added-19 removed
38 unmodified lines39 }40 }41 42 func 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.Stdout48 49 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)56+57 stdin.Close()58 }()59 60 return cmd.Run()13 unmodified lines74 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"))79 80 // 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"))83 84 // 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"))88 89 // 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"))94 95 // 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"}))98 99 // 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 lines109 Run: emptyRun,110 }111 112 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"}))116 117 printCmd := &Command{118 Use: "print [string to print]",119 Args: MinimumNArgs(1),29 unmodified lines149 echoCmd.AddCommand(timesCmd)150 rootCmd.AddCommand(echoCmd, printCmd, deprecatedCmd, colonCmd)151 152 buf := new(bytes.Buffer)152- rootCmd.GenBashCompletion(buf)153+ assertNoErr(t, rootCmd.GenBashCompletion(buf))154 output := buf.String()155 156 check(t, output, "_root")157 check(t, output, "_root_echo")58 unmodified lines216 c := &Command{Use: "c", Run: emptyRun}217 218 const flagName = "hiddenFlag"219 c.Flags().Bool(flagName, false, "")219- c.Flags().MarkHidden(flagName)220+ assertNoErr(t, c.Flags().MarkHidden(flagName))221 222 buf := new(bytes.Buffer)222- c.GenBashCompletion(buf)223+ assertNoErr(t, c.GenBashCompletion(buf))224 output := buf.String()225 226 if strings.Contains(output, flagName) {227 t.Errorf("Expected completion to not include %q flag: Got %v", flagName, output)4 unmodified lines232 c := &Command{Use: "c", Run: emptyRun}233 234 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"))237 238 buf := new(bytes.Buffer)238- c.GenBashCompletion(buf)239+ assertNoErr(t, c.GenBashCompletion(buf))240 output := buf.String()241 242 if strings.Contains(output, flagName) {243 t.Errorf("expected completion to not include %q flag: Got %v", flagName, output)6 unmodified lines250 c.Flags().StringP("string-flag", "s", "", "string flag")251 c.Flags().BoolP("bool-flag", "b", false, "bool flag")252 253 buf := new(bytes.Buffer)253- c.GenBashCompletion(buf)254+ assertNoErr(t, c.GenBashCompletion(buf))255 output := buf.String()256 257 // 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 linesmodified:bash_completions.go+68 added-65 removed
17 unmodified lines18 BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag"19 BashCompSubdirsInDir = "cobra_annotation_bash_completion_subdirs_in_dir"20 )21 22-func writePreamble(buf *bytes.Buffer, name string) {23- buf.WriteString(fmt.Sprintf("# bash completion for %-36s -*- shell-script -*-\n", name))24- buf.WriteString(fmt.Sprintf(`22+func 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 lines379 ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,380 ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))381 }382 383-func writePostscript(buf *bytes.Buffer, name string) {383+func 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; then18 unmodified lines409 __%[1]s_handle_word410 }411 412 `, 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 %s415 else416 complete -o default -o nospace -F __start_%s %s417 fi418 419 `, 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 }422 423-func writeCommands(buf *bytes.Buffer, cmd *Command) {424- buf.WriteString(" commands=()\n")423+func 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 }434 435-func writeFlagHandler(buf *bytes.Buffer, name string, annotations map[string][]string, cmd *Command) {435+func 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))440 441 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))450+451 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))459 460 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 }470 471+const cbn = "\")\n"472+470-func writeShortFlag(buf *bytes.Buffer, flag *pflag.Flag, cmd *Command) {473+func 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 }483 481-func writeFlag(buf *bytes.Buffer, flag *pflag.Flag, cmd *Command) {484+func 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 }498 496-func writeLocalNonPersistentFlag(buf *bytes.Buffer, flag *pflag.Flag) {499+func 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 }510 511 // Setup annotations for go completions for registered flags9 unmodified lines521 flag.Annotations[BashCompCustom] = []string{fmt.Sprintf("__%[1]s_handle_go_custom_completion", cmd.Root().Name())}522 }523 }524 522-func writeFlags(buf *bytes.Buffer, cmd *Command) {525+func 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 lines555 writeShortFlag(buf, flag, cmd)556 }557 })558 556- buf.WriteString("\n")559+ WriteStringAndCheck(buf, "\n")560 }561 559-func writeRequiredFlag(buf *bytes.Buffer, cmd *Command) {560- buf.WriteString(" must_have_one_flag=()\n")562+func 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 return4 unmodified lines572 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))578 579 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 }586 584-func writeRequiredNouns(buf *bytes.Buffer, cmd *Command) {585- buf.WriteString(" must_have_one_noun=()\n")586- sort.Sort(sort.StringSlice(cmd.ValidArgs))587+func 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 }600 598-func writeCmdAliases(buf *bytes.Buffer, cmd *Command) {601+func writeCmdAliases(buf io.StringWriter, cmd *Command) {602 if len(cmd.Aliases) == 0 {603 return604 }605 603- sort.Sort(sort.StringSlice(cmd.Aliases))606+ sort.Strings(cmd.Aliases)607 605- 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 }613-func writeArgAliases(buf *bytes.Buffer, cmd *Command) {614- buf.WriteString(" noun_aliases=()\n")615- sort.Sort(sort.StringSlice(cmd.ArgAliases))616+func 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 }623 621-func gen(buf *bytes.Buffer, cmd *Command) {624+func gen(buf io.StringWriter, cmd *Command) {625 for _, c := range cmd.Commands() {626 if !c.IsAvailableCommand() && c != cmd.helpCommand {627 continue628 }3 unmodified lines632 commandName = strings.Replace(commandName, " ", "_", -1)633 commandName = strings.Replace(commandName, ":", "__", -1)634 635 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 }640 638- 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")645 646 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 }653 654 // GenBashCompletion generates bash completion file and writes to the passed writer.655 func (c *Command) GenBashCompletion(w io.Writer) error {26 unmodified linesmodified:cobra_test.go+6 added
3 unmodified lines4 "testing"5 "text/template"6 )7 8+func assertNoErr(t *testing.T, e error) {9+ if e != nil {10+ t.Error(e)11+ }12+}13+14 func TestAddTemplateFunctions(t *testing.T) {15 AddTemplateFunc("t", func() bool { return true })16 AddTemplateFuncs(template.FuncMap{17 "f": func() bool { return false },11 unmodified linesmodified:cobra.go+15 added
17 unmodified lines18 19 import (20 "fmt"21 "io"22+ "os"23 "reflect"24 "strconv"25 "strings"26 "text/template"178 unmodified lines205 }206 }207 return false208 }209+210+// CheckErr prints the msg with the prefix 'Error:' and exits with error code 1. If the msg is nil, it does nothing.211+func CheckErr(msg interface{}) {212+ if msg != nil {213+ fmt.Fprintln(os.Stderr, "Error:", msg)214+ os.Exit(1)215+ }216+}217+218+// WriteStringAndCheck writes a string into a buffer, and checks if the error is not nil.219+func 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 lines57 t.Errorf("Expected to not contain: \n %v\nGot: %v", expected, got)58 }59 }60 61+const onetwo = "one two"62+63 func TestSingleCommand(t *testing.T) {64 var rootCmdArgs []string65 rootCmd := &Command{66 Use: "root",12 unmodified lines79 t.Errorf("Unexpected error: %v", err)80 }81 82 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 }87 88 func TestChildCommand(t *testing.T) {15 unmodified lines104 t.Errorf("Unexpected error: %v", err)105 }106 107 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 }112 113 func TestCallCommandWithoutSubcommands(t *testing.T) {30 unmodified lines144 t.Errorf("Unexpected error: %v", err)145 }146 147 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 }151 152 func TestExecuteContext(t *testing.T) {89 unmodified lines242 t.Errorf("Unexpected error: %v", err)243 }244 245 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 }250 251 func TestEnablePrefixMatching(t *testing.T) {17 unmodified lines269 t.Errorf("Unexpected error: %v", err)270 }271 272 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 }276 277 EnablePrefixMatching = false278 }25 unmodified lines304 t.Errorf("Unexpected error: %v", err)305 }306 307 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 }311 312 EnablePrefixMatching = false313 }20 unmodified lines334 t.Errorf("Unexpected error: %v", err)335 }336 337 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 }342 343 // TestGrandChildSameName checks the correct behaviour of cobra in cases,19 unmodified lines363 t.Errorf("Unexpected error: %v", err)364 }365 366 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 }371 372 func TestFlagLong(t *testing.T) {27 unmodified lines400 t.Errorf("Expected stringFlagValue: %q, got %q", "abc", stringFlagValue)401 }402 403 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 }408 409 func TestFlagShort(t *testing.T) {24 unmodified lines434 t.Errorf("Expected stringFlagValue: %q, got %q", "abc", stringFlagValue)435 }436 437 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 }442 443 func TestChildFlag(t *testing.T) {193 unmodified lines637 t.Errorf("Unexpected error: %v", err)638 }639 640 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 lines722 t.Errorf("Unexpected error: %v", err)723 }724 725 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 lines736 737 func 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", "", "")744 745 expected := fmt.Sprintf("required flag(s) %q, %q not set", "foo1", "foo2")746 7 unmodified lines754 755 func 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", "", "")762 763 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", "", "")769 770 parent.AddCommand(child)771 11 unmodified lines783 784 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"))788 789 child := &Command{Use: "child", Run: emptyRun}790 child.DisableFlagParsing = true791 497 unmodified lines1289 if err != nil {1290 t.Errorf("Unexpected error: %v", err)1291 }1292 1302- 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 }1308 1309 func TestPersistentHooks(t *testing.T) {1310 var (58 unmodified lines1369 if err != nil {1370 t.Errorf("Unexpected error: %v", err)1371 }1372 1373+ 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- }1395 1407- 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 }1411 1412 // Related to https://github.com/spf13/cobra/issues/521.1413 func TestGlobalNormFuncPropagation(t *testing.T) {314 unmodified lines1728 // Related to https://github.com/spf13/cobra/issues/463.1729 func 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"))1733 1734 output, err := executeCommand(c, "c", "-d")1735 if err != nil {1736 t.Error("Unexpected error:", err)118 unmodified lines1855 args []string1856 call string1857 want string1858 epm bool1871- tc bool1859 }1860 1861 func (tc *calledAsTestcase) test(t *testing.T) {1862 defer func(ov bool) { EnablePrefixMatching = ov }(EnablePrefixMatching)13 unmodified lines1876 output := new(bytes.Buffer)1877 parent.SetOut(output)1878 parent.SetErr(output)1879 1893- parent.Execute()1880+ _ = parent.Execute()1881 1882 if called == nil {1883 if tc.call != "" {1884 t.Errorf("missing expected call to command: %s", tc.call)9 unmodified lines1894 }1895 1896 func 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 }1911 1912 for name, tc := range tests {1913 t.Run(name, tc.test)107 unmodified linesmodified:command.go+57 added-55 removed
82 unmodified lines83 84 // Deprecated defines, if this command is deprecated and should print this string when used.85 Deprecated string86 87- // Hidden defines, if this command is hidden and should NOT show up in the list of available commands.88- Hidden bool89-87 // Annotations are key/value pairs that can be used by applications to identify or88 // group commands.89 Annotations map[string]string90 31 unmodified lines122 PersistentPostRun func(cmd *Command, args []string)123 // PersistentPostRunE: PersistentPostRun but returns an error.124 PersistentPostRunE func(cmd *Command, args []string) error125 129- // SilenceErrors is an option to quiet errors down stream.130- SilenceErrors bool131-132- // SilenceUsage is an option to silence usage when an error occurs.133- SilenceUsage bool134-135- // DisableFlagParsing disables the flag parsing.136- // If this is true all flags will be passed to the command as arguments.137- DisableFlagParsing bool138-139- // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")140- // will be printed by generating docs for this command.141- DisableAutoGenTag bool142-143- // DisableFlagsInUseLine will disable the addition of [flags] to the usage144- // line of a command when printing help or generating docs145- DisableFlagsInUseLine bool146-147- // 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 int153-154- // TraverseChildren parses flags on all parents before executing child command.155- TraverseChildren bool156-157- // FParseErrWhitelist flag parse errors to be ignored158- FParseErrWhitelist FParseErrWhitelist159-160- ctx context.Context161-162- // 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- }177-126 // args is actual args parsed from flags.127 args []string128 // flagErrorBuf contains all error messages from pflag.129 flagErrorBuf *bytes.Buffer33 unmodified lines163 // 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.Writer167+168+ //FParseErrWhitelist flag parse errors to be ignored169+ FParseErrWhitelist FParseErrWhitelist170+171+ // 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+ }178+179+ ctx context.Context180+181+ // 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 int189+190+ // TraverseChildren parses flags on all parents before executing child command.191+ TraverseChildren bool192+193+ // Hidden defines, if this command is hidden and should NOT show up in the list of available commands.194+ Hidden bool195+196+ // SilenceErrors is an option to quiet errors down stream.197+ SilenceErrors bool198+199+ // SilenceUsage is an option to silence usage when an error occurs.200+ SilenceUsage bool201+202+ // DisableFlagParsing disables the flag parsing.203+ // If this is true all flags will be passed to the command as arguments.204+ DisableFlagParsing bool205+206+ // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")207+ // will be printed by generating docs for this command.208+ DisableAutoGenTag bool209+210+ // DisableFlagsInUseLine will disable the addition of [flags] to the usage211+ // line of a command when printing help or generating docs212+ DisableFlagsInUseLine bool213+214+ // DisableSuggestions disables the suggestions based on Levenshtein distance215+ // that go along with 'unknown command' messages.216+ DisableSuggestions bool217+218+ // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.219+ // Must be > 0.220+ SuggestionsMinimumDistance int221 }222 223 // Context returns underlying command context. If command wasn't224 // executed with ExecuteContext Context returns Background context.194 unmodified lines419 bb := new(bytes.Buffer)420 c.outWriter = bb421 c.errWriter = bb422 421- c.Usage()423+ CheckErr(c.Usage())424 425 // Setting things back to normal426 c.outWriter = tmpOutput427 c.errWriter = tmpErr660 unmodified lines1088 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 linesmodified:custom_completions_test.go+23 added-23 removed
778 unmodified lines779 }780 rootCmd.AddCommand(childCmd)781 782 rootCmd.Flags().IntP("requiredFlag", "r", -1, "required flag")783- rootCmd.MarkFlagRequired("requiredFlag")783+ assertNoErr(t, rootCmd.MarkFlagRequired("requiredFlag"))784 requiredFlag := rootCmd.Flags().Lookup("requiredFlag")785 786 rootCmd.PersistentFlags().IntP("requiredPersistent", "p", -1, "required persistent")787- rootCmd.MarkPersistentFlagRequired("requiredPersistent")787+ assertNoErr(t, rootCmd.MarkPersistentFlagRequired("requiredPersistent"))788 requiredPersistent := rootCmd.PersistentFlags().Lookup("requiredPersistent")789 790 rootCmd.Flags().StringP("release", "R", "", "Release name")791 792 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")795 796 // Test that a required flag is suggested even without the - prefix797 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")165 unmodified lines963 }964 965 // No extensions. Should be ignored.966 rootCmd.Flags().StringP("file", "f", "", "file flag")967- rootCmd.MarkFlagFilename("file")967+ assertNoErr(t, rootCmd.MarkFlagFilename("file"))968 969 // Single extension970 rootCmd.Flags().StringP("log", "l", "", "log flag")971- rootCmd.MarkFlagFilename("log", "log")971+ assertNoErr(t, rootCmd.MarkFlagFilename("log", "log"))972 973 // Multiple extensions974 rootCmd.Flags().StringP("yaml", "y", "", "yaml flag")975- rootCmd.MarkFlagFilename("yaml", "yaml", "yml")975+ assertNoErr(t, rootCmd.MarkFlagFilename("yaml", "yaml", "yml"))976 977 // 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"}))980 981 // 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 lines1085 }1086 1087 // Filter directories1088 rootCmd.Flags().StringP("dir", "d", "", "dir flag")1089- rootCmd.MarkFlagDirname("dir")1089+ assertNoErr(t, rootCmd.MarkFlagDirname("dir"))1090 1091 // 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"}))1094 1095 // 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"}))1098 1099 // 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 lines1429 }1430 rootCmd.AddCommand(child)1431 1432 buf := new(bytes.Buffer)1433- rootCmd.GenBashCompletion(buf)1433+ assertNoErr(t, rootCmd.GenBashCompletion(buf))1434 output := buf.String()1435 1436 check(t, output, "has_completion_function=1")1437 }6 unmodified lines1444 }1445 rootCmd.AddCommand(child)1446 1447 buf := new(bytes.Buffer)1448- rootCmd.GenBashCompletion(buf)1448+ assertNoErr(t, rootCmd.GenBashCompletion(buf))1449 output := buf.String()1450 1451 checkOmit(t, output, "has_completion_function=1")1452 }7 unmodified lines1460 }1461 rootCmd.AddCommand(child)1462 1463 buf := new(bytes.Buffer)1464- rootCmd.GenBashCompletion(buf)1464+ assertNoErr(t, rootCmd.GenBashCompletion(buf))1465 output := buf.String()1466 1467 check(t, output, ShellCompNoDescRequestCmd)1468 }7 unmodified lines1476 }1477 rootCmd.AddCommand(child)1478 1479 buf := new(bytes.Buffer)1480- rootCmd.GenZshCompletionNoDesc(buf)1480+ assertNoErr(t, rootCmd.GenZshCompletionNoDesc(buf))1481 output := buf.String()1482 1483 check(t, output, ShellCompNoDescRequestCmd)1484 }7 unmodified lines1492 }1493 rootCmd.AddCommand(child)1494 1495 buf := new(bytes.Buffer)1496- rootCmd.GenZshCompletion(buf)1496+ assertNoErr(t, rootCmd.GenZshCompletion(buf))1497 output := buf.String()1498 1499 check(t, output, ShellCompRequestCmd)1500 checkOmit(t, output, ShellCompNoDescRequestCmd)4 unmodified lines1505 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+ }))1528 1529 // Test completing an empty string1530 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--introot", "")1531 if err != nil {170 unmodified lines1702 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+ }))1725 1726 // Test completing an empty string1727 output, err := executeCommand(rootCmd, ShellCompRequestCmd, "--introot", "")1728 if err != nil {232 unmodified linesmodified:custom_completions.go+2 added-2 removed
525 unmodified lines526 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 }533 534 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 }539 540 // CompDebugln prints the specified string with a newline at the end17 unmodified linesmodified:fish_completions_test.go+4 added-4 removed
13 unmodified lines14 }15 rootCmd.AddCommand(child)16 17 buf := new(bytes.Buffer)18- rootCmd.GenFishCompletion(buf, false)18+ assertNoErr(t, rootCmd.GenFishCompletion(buf, false))19 output := buf.String()20 21 check(t, output, ShellCompNoDescRequestCmd)22 }7 unmodified lines30 }31 rootCmd.AddCommand(child)32 33 buf := new(bytes.Buffer)34- rootCmd.GenFishCompletion(buf, true)34+ assertNoErr(t, rootCmd.GenFishCompletion(buf, true))35 output := buf.String()36 37 check(t, output, ShellCompRequestCmd)38 checkOmit(t, output, ShellCompNoDescRequestCmd)1 unmodified line40 41 func 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()46 47 // Functions name should have replace the '-'48 check(t, output, "__root_dash_perform_completion")6 unmodified lines55 56 func 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()61 62 // Functions name should have replace the ':'63 check(t, output, "__root_colon_perform_completion")6 unmodified linesmodified:fish_completions.go+3 added-3 removed
6 unmodified lines7 "os"8 "strings"9 )10 11-func genFishComp(buf *bytes.Buffer, name string, includeDesc bool) {11+func 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 line17 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(`23 function __%[1]s_debug24 set file "$BASH_COMP_DEBUG_FILE"25 if test -n "$file"26 echo "$argv" >> $file181 unmodified linesmodified:Makefile+11 added-7 removed
1 BIN="./bin"2 SRC=$(shell find . -name "*.go")3 4+ifeq (, $(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")6+endif7+8 ifeq (, $(shell which richgo))9 $(warning "could not find richgo in $(PATH), run: go get github.com/kyoh86/richgo")10 endif11 8-.PHONY: fmt vet test cobra_generator install_deps clean12+.PHONY: fmt lint test cobra_generator install_deps clean13 14 default: all15 12-all: fmt vet test cobra_generator 16+all: fmt test cobra_generator17 18 fmt:19 $(info ******************** checking formatting ********************)20 @test -z $(shell gofmt -l $(SRC)) || (gofmt -d $(SRC); exit 1)21 22+lint:23+ $(info ******************** running lint tools ********************)24+ golangci-lint run -v25+18-test: install_deps vet26+test: install_deps lint27 $(info ******************** running tests ********************)28 richgo test -v ./...29 30 cobra_generator: install_deps4 unmodified lines35 install_deps:36 $(info ******************** downloading dependencies ********************)37 go get -v ./...38 31-vet:32- $(info ******************** vetting ********************)33- go vet ./...34-39 clean:40 rm -rf $(BIN)modified:powershell_completions.go+13 added-13 removed
8 unmodified lines9 "io"10 "os"11 )12 13-func genPowerShellComp(buf *bytes.Buffer, name string, includeDesc bool) {13+func 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 -*-19 20 function __%[1]s_debug {21 if ($env:BASH_COMP_DEBUG_FILE) {22 "$args" | Out-File -Append -FilePath "$env:BASH_COMP_DEBUG_FILE"22 unmodified lines45 # 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- 54+55 $ShellCompDirectiveError=%[3]d56 $ShellCompDirectiveNoSpace=%[4]d57 $ShellCompDirectiveNoFileComp=%[5]d58 $ShellCompDirectiveFilterFileExt=%[6]d4 unmodified lines63 $Program,$Arguments = $Command.Split(" ",2)64 $RequestComp="$Program %[2]s $Arguments"65 __%[1]s_debug "RequestComp: $RequestComp"66 67- # 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 lines101 # There is no directive specified102 $Directive = 0103 }104 __%[1]s_debug "The completion directive is: $Directive"105- 105+106 # remove directive (last element) from out107 $Out = $Out | Where-Object { $_ -ne $Out[-1] }108 __%[1]s_debug "The completions are: $Out"109 31 unmodified lines141 }142 143 if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) {144 __%[1]s_debug "ShellCompDirectiveNoFileComp is called"145- 145+146 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 }155 156- 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"159 160 # return here to prevent the completion of the extensions8 unmodified lines169 if ( $IsEqualFlag ) {170 __%[1]s_debug "Join the equal sign flag back to the completion value"171 $_.Name = $Flag + "=" + $_.Name172 }173- } 173+ }174 175 # Get the current mode176 $Mode = (Get-PSReadLineKeyHandler | Where-Object {$_.Key -eq "Tab" }).Function177 __%[1]s_debug "Mode: $Mode"45 unmodified lines223 224 # 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 }231 232 # 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 linesmodified:README.md+1 added-8 removed
232 unmodified lines233 rootCmd.AddCommand(addCmd)234 rootCmd.AddCommand(initCmd)235 }236 237-func er(msg interface{}) {238- fmt.Println("Error:", msg)239- os.Exit(1)240-}241-237 func 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)245 246 // Search config in home directory with name ".cobra" (without extension).247 viper.AddConfigPath(home)248 viper.SetConfigName(".cobra")511 unmodified linesmodified:shell_completions.md+3 added-4 removed
97 unmodified lines98 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 lines130 the completion algorithm if entered manually, e.g. in:131 132 ```bash133 $ kubectl get rc [tab][tab]135-backend frontend database 134+backend frontend database135 ```136 137 Note that without declaring `rc` as an alias, the completion algorithm would not know to show the list of138 replication controllers following `rc`.113 unmodified lines252 and you'll get something like253 254 ```bash255 $ kubectl exec [tab][tab]257--c --container= -p --pod= 256+-c --container= -p --pod=257 ```258 259 ### Specify dynamic flag completion260 223 unmodified linesmodified:zsh_completions.go+2 added-2 removed
68 unmodified lines69 _, err := buf.WriteTo(w)70 return err71 }72 73-func genZshComp(buf *bytes.Buffer, name string, includeDesc bool) {73+func 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]s79 80 # zsh completion for %-36[1]s -*- shell-script -*-81 82 __%[1]s_debug()158 unmodified lines