Skip to content

Commit

Permalink
Make configuring commands more generic
Browse files Browse the repository at this point in the history
- VisitCommands takes a list of functions to apply
- Rename ReconfigureLeafCmd->ReconfigureLeafCmds b/c there may be many leafs
- ReconfigureLeaf takes functions to apply to leaf commands
- Introduce DisallowExtraArgs reconfigure function
  • Loading branch information
ewrenn8 committed May 14, 2020
1 parent a0f6e0d commit 70d8ba8
Showing 1 changed file with 31 additions and 22 deletions.
53 changes: 31 additions & 22 deletions misc.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,30 @@ import (
"github.com/spf13/cobra"
)

func VisitCommands(cmd *cobra.Command, f func(*cobra.Command)) {
f(cmd)
type ReconfigureFunc func(cmd *cobra.Command)

func VisitCommands(cmd *cobra.Command, fns ...ReconfigureFunc) {
for _, f := range fns {
f(cmd)
}
for _, child := range cmd.Commands() {
VisitCommands(child, f)
VisitCommands(child, fns...)
}
}

func ReconfigureLeafCmds(fs ...func(cmd *cobra.Command)) ReconfigureFunc {
return func(cmd *cobra.Command) {
if len(cmd.Commands()) > 0 {
return
}

for _, f := range fs {
f(cmd)
}
}
}

func WrapRunEForCmd(additionalRunE func(*cobra.Command, []string) error) func(cmd *cobra.Command) {
func WrapRunEForCmd(additionalRunE func(*cobra.Command, []string) error) ReconfigureFunc {
return func(cmd *cobra.Command) {
if cmd.RunE == nil {
panic(fmt.Sprintf("Internal: Command '%s' does not set RunE", cmd.CommandPath()))
Expand All @@ -31,6 +47,8 @@ func WrapRunEForCmd(additionalRunE func(*cobra.Command, []string) error) func(cm
}
}

// ReconfigureFuncs

func ReconfigureCmdWithSubcmd(cmd *cobra.Command) {
if len(cmd.Commands()) == 0 {
return
Expand All @@ -53,27 +71,18 @@ func ReconfigureCmdWithSubcmd(cmd *cobra.Command) {
cmd.Short += " (" + strings.Join(strs, ", ") + ")"
}

func ReconfigureLeafCmd(cmd *cobra.Command) {
if len(cmd.Commands()) > 0 {
return
}

if cmd.RunE == nil {
panic(fmt.Sprintf("Internal: Command '%s' does not set RunE", cmd.CommandPath()))
}

if cmd.Args == nil {
origRunE := cmd.RunE
cmd.RunE = func(cmd2 *cobra.Command, args []string) error {
if len(args) > 0 {
return fmt.Errorf("command '%s' does not accept extra arguments '%s'", cmd2.CommandPath(), args[0])
}
return origRunE(cmd2, args)
func DisallowExtraArgs(cmd *cobra.Command) {
WrapRunEForCmd(func(cmd2 *cobra.Command, args []string) error {
if len(args) > 0 {
return fmt.Errorf("command '%s' does not accept extra arguments '%s'", cmd2.CommandPath(), args[0])
}
cmd.Args = cobra.ArbitraryArgs
}
return nil
})(cmd)
cmd.Args = cobra.ArbitraryArgs
}

// New RunE's

func ShowSubcommands(cmd *cobra.Command, args []string) error {
var strs []string
for _, subcmd := range cmd.Commands() {
Expand Down

0 comments on commit 70d8ba8

Please sign in to comment.