Skip to content

Commit

Permalink
Display custom command usage when it has no step (#264)
Browse files Browse the repository at this point in the history
Use a Cobra PreRun function to end or abort a custom command when its
invocation is incorrect or incomplete.

Co-authored-by: Andriy Knysh <aknysh@users.noreply.github.com>
  • Loading branch information
stoned and aknysh committed Nov 28, 2022
1 parent 4003778 commit a817870
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions cmd/cmd_utils.go
Expand Up @@ -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)
},
Expand Down Expand Up @@ -94,15 +97,26 @@ 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) {
err = fmt.Errorf("invalid number of arguments, %d argument(s) required", len(commandConfig.Arguments))
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
Expand Down

0 comments on commit a817870

Please sign in to comment.