@@ -3,6 +3,7 @@ package core
33import (
44 "fmt"
55 "reflect"
6+ "strconv"
67 "strings"
78
89 "github.com/scaleway/scaleway-cli/internal/args"
@@ -13,19 +14,19 @@ import (
1314
1415// CommandValidateFunc validates en entire command.
1516// Used in core.cobraRun().
16- type CommandValidateFunc func (cmd * Command , cmdArgs interface {}) error
17+ type CommandValidateFunc func (cmd * Command , cmdArgs interface {}, rawArgs args. RawArgs ) error
1718
1819// ArgSpecValidateFunc validates one argument of a command.
1920type ArgSpecValidateFunc func (argSpec * ArgSpec , value interface {}) error
2021
2122// DefaultCommandValidateFunc is the default validation function for commands.
2223func DefaultCommandValidateFunc () CommandValidateFunc {
23- return func (cmd * Command , cmdArgs interface {}) error {
24+ return func (cmd * Command , cmdArgs interface {}, rawArgs args. RawArgs ) error {
2425 err := validateArgValues (cmd , cmdArgs )
2526 if err != nil {
2627 return err
2728 }
28- err = validateRequiredArgs (cmd , cmdArgs )
29+ err = validateRequiredArgs (cmd , cmdArgs , rawArgs )
2930 if err != nil {
3031 return err
3132 }
@@ -59,8 +60,13 @@ func validateArgValues(cmd *Command, cmdArgs interface{}) error {
5960// validateRequiredArgs checks for missing required args with no default value.
6061// Returns an error for the first missing required arg.
6162// Returns nil otherwise.
62- func validateRequiredArgs (cmd * Command , cmdArgs interface {}) error {
63+ // TODO refactor this method which uses a mix of reflect and string arrays
64+ func validateRequiredArgs (cmd * Command , cmdArgs interface {}, rawArgs args.RawArgs ) error {
6365 for _ , arg := range cmd .ArgSpecs {
66+ if ! arg .Required {
67+ continue
68+ }
69+
6470 fieldName := strcase .ToPublicGoName (arg .Name )
6571 fieldValues , err := getValuesForFieldByName (reflect .ValueOf (cmdArgs ), strings .Split (fieldName , "." ))
6672 if err != nil {
@@ -72,9 +78,13 @@ func validateRequiredArgs(cmd *Command, cmdArgs interface{}) error {
7278 panic (validationErr )
7379 }
7480
75- for _ , fieldValue := range fieldValues {
76- if arg .Required && (fieldValue .IsZero () || ! fieldValue .IsValid ()) {
77- return MissingRequiredArgumentError (arg .Name )
81+ // Either fieldsValues have a length for 1 and we check for existence in the rawArgs
82+ // or it has multiple values and we loop through each one to get the right element in
83+ // the corresponding rawArgs array and replace {index} by the element's index.
84+ // TODO handle required maps
85+ for i := range fieldValues {
86+ if ! rawArgs .ExistsArgByName (strings .Replace (arg .Name , "{index}" , strconv .Itoa (i ), 1 )) {
87+ return MissingRequiredArgumentError (strings .Replace (arg .Name , "{index}" , strconv .Itoa (i ), 1 ))
7888 }
7989 }
8090 }
0 commit comments