forked from scaleway/scaleway-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidate.go
171 lines (154 loc) · 5.18 KB
/
validate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
package core
import (
"fmt"
"reflect"
"strconv"
"strings"
"github.com/scaleway/scaleway-cli/internal/args"
"github.com/scaleway/scaleway-sdk-go/logger"
"github.com/scaleway/scaleway-sdk-go/strcase"
"github.com/scaleway/scaleway-sdk-go/validation"
)
// CommandValidateFunc validates en entire command.
// Used in core.cobraRun().
type CommandValidateFunc func(cmd *Command, cmdArgs interface{}, rawArgs args.RawArgs) error
// ArgSpecValidateFunc validates one argument of a command.
type ArgSpecValidateFunc func(argSpec *ArgSpec, value interface{}) error
// DefaultCommandValidateFunc is the default validation function for commands.
func DefaultCommandValidateFunc() CommandValidateFunc {
return func(cmd *Command, cmdArgs interface{}, rawArgs args.RawArgs) error {
err := validateArgValues(cmd, cmdArgs)
if err != nil {
return err
}
err = validateRequiredArgs(cmd, cmdArgs, rawArgs)
if err != nil {
return err
}
return nil
}
}
// validateArgValues validates values passed to the different args of a Command.
func validateArgValues(cmd *Command, cmdArgs interface{}) error {
for _, argSpec := range cmd.ArgSpecs {
fieldName := strcase.ToPublicGoName(argSpec.Name)
fieldValues, err := getValuesForFieldByName(reflect.ValueOf(cmdArgs), strings.Split(fieldName, "."))
if err != nil {
logger.Infof("could not validate arg value for '%v': invalid fieldName: %v: %v", argSpec.Name, fieldName, err.Error())
continue
}
validateFunc := DefaultArgSpecValidateFunc()
if argSpec.ValidateFunc != nil {
validateFunc = argSpec.ValidateFunc
}
for _, fieldValue := range fieldValues {
err := validateFunc(argSpec, fieldValue.Interface())
if err != nil {
return err
}
}
}
return nil
}
// validateRequiredArgs checks for missing required args with no default value.
// Returns an error for the first missing required arg.
// Returns nil otherwise.
// TODO refactor this method which uses a mix of reflect and string arrays
func validateRequiredArgs(cmd *Command, cmdArgs interface{}, rawArgs args.RawArgs) error {
for _, arg := range cmd.ArgSpecs {
if !arg.Required {
continue
}
fieldName := strcase.ToPublicGoName(arg.Name)
fieldValues, err := getValuesForFieldByName(reflect.ValueOf(cmdArgs), strings.Split(fieldName, "."))
if err != nil {
validationErr := fmt.Errorf("could not validate arg value for '%v': invalid field name '%v': %v", arg.Name, fieldName, err.Error())
if !arg.Required {
logger.Infof(validationErr.Error())
continue
}
panic(validationErr)
}
// Either fieldsValues have a length for 1 and we check for existence in the rawArgs
// or it has multiple values and we loop through each one to get the right element in
// the corresponding rawArgs array and replace {index} by the element's index.
// TODO handle required maps
for i := range fieldValues {
if !rawArgs.ExistsArgByName(strings.Replace(arg.Name, "{index}", strconv.Itoa(i), 1)) {
return MissingRequiredArgumentError(strings.Replace(arg.Name, "{index}", strconv.Itoa(i), 1))
}
}
}
return nil
}
// DefaultArgSpecValidateFunc validates a value passed for an ArgSpec
// Uses ArgSpec.EnumValues
func DefaultArgSpecValidateFunc() ArgSpecValidateFunc {
return func(argSpec *ArgSpec, value interface{}) error {
if len(argSpec.EnumValues) < 1 {
return nil
}
strValue, err := args.MarshalValue(value)
if err != nil {
return err
}
// When an enum is not provided as an argument args.MarshalValue will in most cases return "" (go default value)
// In those cases we ignore validation. This is not ideal but covers most of the use cases.
// The only caveat would be that `my-enum=""` would not trigger an error, which is acceptable.
if strValue == "" {
return nil
}
if !stringExists(argSpec.EnumValues, strValue) {
return InvalidValueForEnumError(argSpec.Name, argSpec.EnumValues, strValue)
}
return nil
}
}
func stringExists(strs []string, s string) bool {
for _, s2 := range strs {
if s == s2 {
return true
}
}
return false
}
func ValidateSecretKey() ArgSpecValidateFunc {
return func(argSpec *ArgSpec, valueI interface{}) error {
value := valueI.(string)
err := DefaultArgSpecValidateFunc()(argSpec, value)
if err != nil {
return err
}
if !validation.IsSecretKey(value) {
return InvalidSecretKeyError(value)
}
return nil
}
}
// ValidateOrganizationID validates a non-required organization ID.
// By default, for most command, the organization ID is not required.
// In that case, we allow the empty-string value "".
func ValidateOrganizationID() ArgSpecValidateFunc {
return func(argSpec *ArgSpec, valueI interface{}) error {
value := valueI.(string)
if value == "" && !argSpec.Required {
return nil
}
return ValidateOrganizationIDRequired()(argSpec, valueI)
}
}
// ValidateOrganizationIDRequired validates a required organization ID.
// We do not allow empty-string value "".
func ValidateOrganizationIDRequired() ArgSpecValidateFunc {
return func(argSpec *ArgSpec, valueI interface{}) error {
value := valueI.(string)
err := DefaultArgSpecValidateFunc()(argSpec, value)
if err != nil {
return err
}
if !validation.IsOrganizationID(value) {
return InvalidOrganizationIDError(value)
}
return nil
}
}