Skip to content

Commit

Permalink
Implement slightly wonky setup for checking against ...
Browse files Browse the repository at this point in the history
subcommand names of a default command (should it be set)
  • Loading branch information
jalavosus committed May 6, 2022
1 parent 0c6e6bb commit 027026b
Showing 1 changed file with 30 additions and 6 deletions.
36 changes: 30 additions & 6 deletions app.go
Original file line number Diff line number Diff line change
Expand Up @@ -316,14 +316,26 @@ func (a *App) RunContext(ctx context.Context, arguments []string) (err error) {
if a.validCommandName(name) {
c = a.Command(name)
} else {
isFlagName := false
for _, flagName := range cCtx.FlagNames() {
if name == flagName {
isFlagName = true
break
hasDefault := a.DefaultCommand != ""
isFlagName := checkStringSliceIncludes(name, cCtx.FlagNames())

var (
isDefaultSubcommand = false
defaultHasSubcommands = false
)

if hasDefault {
dc := a.Command(a.DefaultCommand)
defaultHasSubcommands = len(dc.Subcommands) > 0
for _, dcSub := range dc.Subcommands {
if checkStringSliceIncludes(name, dcSub.Names()) {
isDefaultSubcommand = true
break
}
}
}
if isFlagName {

if isFlagName || (hasDefault && (defaultHasSubcommands && isDefaultSubcommand)) {
argsWithDefault := a.argsWithDefaultCommand(args)
if !reflect.DeepEqual(args, argsWithDefault) {
c = a.Command(argsWithDefault.First())
Expand All @@ -349,6 +361,18 @@ func (a *App) RunContext(ctx context.Context, arguments []string) (err error) {
return err
}

func checkStringSliceIncludes(want string, sSlice []string) bool {
found := false
for _, s := range sSlice {
if want == s {
found = true
break
}
}

return found
}

// RunAndExitOnError calls .Run() and exits non-zero if an error was returned
//
// Deprecated: instead you should return an error that fulfills cli.ExitCoder
Expand Down

0 comments on commit 027026b

Please sign in to comment.