From 788165dd5d4adc82b6dd6a3bec7b6b45190bdfe6 Mon Sep 17 00:00:00 2001 From: Stoned Elipot Date: Sat, 26 Nov 2022 19:14:18 +0100 Subject: [PATCH] Display custom command usage when it has no step Use a Cobra PreRun function to end or abort a custom command when its invocation is incorrect or incomplete. --- cmd/cmd_utils.go | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/cmd/cmd_utils.go b/cmd/cmd_utils.go index 8f7ca7f06..1be5da941 100644 --- a/cmd/cmd_utils.go +++ b/cmd/cmd_utils.go @@ -51,6 +51,9 @@ func processCustomCommands(commands []cfg.Command, parentCommand *cobra.Command, Use: commandConfig.Name, Short: commandConfig.Description, Long: commandConfig.Description, + PreRun: func(cmd *cobra.Command, args []string) { + preCustomCommand(cmd, args, parentCommand, commandConfig) + }, Run: func(cmd *cobra.Command, args []string) { executeCustomCommand(cmd, args, parentCommand, commandConfig) }, @@ -94,8 +97,8 @@ func processCustomCommands(commands []cfg.Command, parentCommand *cobra.Command, return nil } -// executeCustomCommand executes a custom command -func executeCustomCommand(cmd *cobra.Command, args []string, parentCommand *cobra.Command, commandConfig *cfg.Command) { +// preCustomCommand is run before a custom command is executed +func preCustomCommand(cmd *cobra.Command, args []string, parentCommand *cobra.Command, commandConfig *cfg.Command) { var err error if len(args) != len(commandConfig.Arguments) { @@ -103,6 +106,17 @@ func executeCustomCommand(cmd *cobra.Command, args []string, parentCommand *cobr u.PrintErrorToStdErrorAndExit(err) } + // no steps means a sub command should be specified + if len(commandConfig.Steps) == 0 { + cmd.Help() + os.Exit(0) + } +} + +// executeCustomCommand executes a custom command +func executeCustomCommand(cmd *cobra.Command, args []string, parentCommand *cobra.Command, commandConfig *cfg.Command) { + var err error + // Execute custom command's steps for i, step := range commandConfig.Steps { // Prepare template data for arguments