I want sub command to print out the Help menu if no argument or flags is passed (The main command does this by default).
For example, the main command without any arguments or flags:
chris@pop-os:~$ ./tk
Command line application to deploy
Usage:
tk [command]
Available Commands:
addon Install packages
cluster Used to create cloud infrastructures
help Help about any command
Flags:
--config string config file (default is $HOME/.tk8.yaml)
-h, --help help for tk
-t, --toggle Help message for toggle
Use "tk [command] --help" for more information about a command.
I want subcommand like "tk addon" to also return it's own help menu if no arguments or flags is entered, currently it only gives a blank line.
addon code :
var addonCmd = &cobra.Command{
Use: "addon",
Short: "Install addon packages",
Long: `Install additional packages`,
Run: func(cmd *cobra.Command, args []string) {
}
},
}
It is possible to do with checking of amount of passed arguments to your program. If there is more then 0
args you will do actual work, but if it less then you will just show the "help" for the command.
var addonCmd = &cobra.Command{
Use: "addon",
Short: "Install addon packages",
Long: `Install additional packages`,
Run: func(cmd *cobra.Command, args []string) {
if len(args) == 0 {
cmd.Help()
os.Exit(0)
}
// do actual work
},
}
I think it is better to handle that on PreRunE.
var addonCmd = &cobra.Command{
Use: "addon",
Short: "Install addon packages",
Long: `Install additional packages`,
PreRunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
cmd.Help()
os.Exit(0)
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
// do actual work
},
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With