Skip to content

Commit

Permalink
removed duplicated code and simplified a little in validate
Browse files Browse the repository at this point in the history
  • Loading branch information
mailund committed Jul 2, 2021
1 parent 7f03c3c commit 5e30d5a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 15 deletions.
8 changes: 6 additions & 2 deletions commands_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ func TestCommandCalled(t *testing.T) {
}
}

func TestOption(t *testing.T) {
func TestOption(t *testing.T) { //nolint:funlen // it's okay to be long
called := false

type argv struct {
Expand Down Expand Up @@ -208,7 +208,11 @@ func TestOption(t *testing.T) {

builder := new(strings.Builder)
cmd.SetOutput(builder)
cmd.Run([]string{"-x", "foo"}) // wrong type for int

err = cmd.RunError([]string{"-x", "foo"}) // wrong type for int
if err == nil {
t.Error("expected an error")
}

if called {
t.Error("The command shouldn't be called")
Expand Down
26 changes: 13 additions & 13 deletions validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,29 @@ import (
"github.com/mailund/cli/interfaces"
)

func validate(flag bool, v interface{}) error {
if val, ok := v.(interfaces.Validator); ok {
return val.Validate(flag)
}

return nil
}

func validateFlagsAndParams(cmd *Command) error {
for i := 0; i < cmd.flags.NFlags(); i++ {
if v, ok := cmd.flags.Flag(i).Value.(interfaces.Validator); ok {
if err := v.Validate(true); err != nil {
return err
}
if err := validate(true, cmd.flags.Flag(i).Value); err != nil {
return err
}
}

for i := 0; i < cmd.params.NParams(); i++ {
if v, ok := cmd.params.Param(i).Value.(interfaces.Validator); ok {
if err := v.Validate(false); err != nil {
return err
}
if err := validate(false, cmd.params.Param(i).Value); err != nil {
return err
}
}

if vv := cmd.params.Variadic(); vv != nil {
if v, ok := vv.Value.(interfaces.Validator); ok {
if err := v.Validate(false); err != nil {
return err
}
}
return validate(false, vv.Value)
}

return nil
Expand Down

0 comments on commit 5e30d5a

Please sign in to comment.