From 97f90a54e490db88c75ec5a1cb915fbf61a60e70 Mon Sep 17 00:00:00 2001 From: Oleg Kovalov Date: Mon, 1 Nov 2021 19:36:50 +0100 Subject: [PATCH] Extract subcommands validation to a func --- acmd.go | 49 ++++++++++++++++++++++++++++--------------------- 1 file changed, 28 insertions(+), 21 deletions(-) diff --git a/acmd.go b/acmd.go index 434deab..024cf67 100644 --- a/acmd.go +++ b/acmd.go @@ -171,27 +171,34 @@ func validateCommand(cmd Command) error { return fmt.Errorf("command alias %q must contains only letters, digits, - and _", cmd.Alias) case len(cmds) != 0: - sort.Slice(cmds, func(i, j int) bool { - return cmds[i].Name < cmds[j].Name - }) - - names := make(map[string]struct{}) - for _, cmd := range cmds { - if _, ok := names[cmd.Name]; ok { - return fmt.Errorf("duplicate command %q", cmd.Name) - } - if _, ok := names[cmd.Alias]; ok { - return fmt.Errorf("duplicate command alias %q", cmd.Alias) - } - - names[cmd.Name] = struct{}{} - if cmd.Alias != "" { - names[cmd.Alias] = struct{}{} - } - - if err := validateCommand(cmd); err != nil { - return err - } + if err := validateSubcommands(cmds); err != nil { + return err + } + } + return nil +} + +func validateSubcommands(cmds []Command) error { + sort.Slice(cmds, func(i, j int) bool { + return cmds[i].Name < cmds[j].Name + }) + + names := make(map[string]struct{}) + for _, cmd := range cmds { + if _, ok := names[cmd.Name]; ok { + return fmt.Errorf("duplicate command %q", cmd.Name) + } + if _, ok := names[cmd.Alias]; ok { + return fmt.Errorf("duplicate command alias %q", cmd.Alias) + } + + names[cmd.Name] = struct{}{} + if cmd.Alias != "" { + names[cmd.Alias] = struct{}{} + } + + if err := validateCommand(cmd); err != nil { + return err } } return nil