Skip to content
Myr

Return an error in the case of unrunnable subcommand

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

* credit to @chriswhelix for initial commit

authored by Bruce Downs · committed by Albert Nigmatzianov · parent 9552679 · Browse files · 2 files+16 added−4 removed
This commit

State

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

Diff stats

2 files+16 added−4 removed

  • other:+16 added−4 removed

2 files+16 added−4 removed

modified:command_test.go+2 added-2 removed
834 unmodified lines
835 childCmd := &Command{Use: "child", Long: "Long description"}836 rootCmd.AddCommand(childCmd)837838 output, err := executeCommand(rootCmd, "child")839 if err != nil {840 t.Errorf("Unexpected error: %v", err)839 if err != NotRunnable {840 t.Errorf("Expected error")841 }842843 checkStringContains(t, output, childCmd.Long)844}
931 unmodified lines
modified:command.go+14 added-2 removed
15 unmodified lines
16package cobra1718import (19 "bytes"20 "errors"21 "fmt"22 "io"23 "os"24 "path/filepath"
2 unmodified lines
2728 flag "github.com/spf13/pflag"29)3031// NotRunnable defines subcommand error32var NotRunnable = errors.New("subcommand is required")3334// FParseErrWhitelist configures Flag parse errors to be ignored35type FParseErrWhitelist flag.ParseErrorsWhitelist3637// Command is just that, a command for your application.
334 unmodified lines
372 return c.Parent().HelpFunc()373 }374 return func(c *Command, a []string) {375 c.mergePersistentFlags()372 err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c)376 err := tmpl(c.OutOrStderr(), c.HelpTemplate(), c)377 if err != nil {378 c.Println(err)379 }380 }
408 unmodified lines
789 }790 }791792 if !c.Runnable() {789 return flag.ErrHelp793 return NotRunnable794 }795796 c.preRun()797
125 unmodified lines
923 cmd.HelpFunc()(cmd, args)924 return cmd, nil925 }926927 // If command wasn't runnable, show full help, but do return the error.928 // This will result in apps by default returning a non-success exit code, but also gives them the option to929 // handle specially.930 if err == NotRunnable {931 cmd.HelpFunc()(cmd, args)932 return cmd, err933 }934935 // If root command has SilentErrors flagged,936 // all subcommands should respect it937 if !cmd.SilenceErrors && !c.SilenceErrors {938 c.Println("Error:", err.Error())
668 unmodified lines