commands: Cleanup up argument validation
Matt Bell committed
Nov 16, 2014 at 23:55 UTC
bc8a97c119393060b242605ec05ec770b68825ba
1 file changed
+7
-27
commands/command.go
+7
-27
@@ -3,7 +3,6 @@ package commands
3
import (
4
"errors"
5
"fmt"
6
- "io"
6
"reflect"
7
"strings"
8
@@ -195,9 +194,6 @@ func (c *Command) GetOptions(path []string) (map[string]Option, error) {
194
}
195
196
func (c *Command) CheckArguments(req Request) error {
198
-
199
- // TODO: check file arguments
200
-
197
args := req.Arguments()
198
199
// count required argument definitions
@@ -217,13 +213,14 @@ func (c *Command) CheckArguments(req Request) error {
213
}
214
215
// the value for this argument definition. can be nil if it wasn't provided by the caller
220
- var v interface{}
216
+ v, found := "", false
217
if valueIndex < len(args) {
218
v = args[valueIndex]
219
+ found = true
220
valueIndex++
221
}
222
226
- err := checkArgValue(v, argDef)
223
+ err := checkArgValue(v, found, argDef)
224
if err != nil {
225
return err
226
}
@@ -231,7 +228,7 @@ func (c *Command) CheckArguments(req Request) error {
228
// any additional values are for the variadic arg definition
229
if argDef.Variadic && valueIndex < len(args)-1 {
230
for _, val := range args[valueIndex:] {
234
- err := checkArgValue(val, argDef)
231
+ err := checkArgValue(val, true, argDef)
232
if err != nil {
233
return err
234
}
@@ -248,26 +245,9 @@ func (c *Command) Subcommand(id string) *Command {
245
}
246
247
// checkArgValue returns an error if a given arg value is not valid for the given Argument
251
-func checkArgValue(v interface{}, def Argument) error {
252
- if v == nil {
253
- if def.Required {
254
- return fmt.Errorf("Argument '%s' is required", def.Name)
255
- }
256
-
257
- return nil
258
- }
259
-
260
- if def.Type == ArgFile {
261
- _, ok := v.(io.Reader)
262
- if !ok {
263
- return fmt.Errorf("Argument '%s' isn't valid", def.Name)
264
- }
265
-
266
- } else if def.Type == ArgString {
267
- _, ok := v.(string)
268
- if !ok {
269
- return fmt.Errorf("Argument '%s' must be a string", def.Name)
270
- }
248
+func checkArgValue(v string, found bool, def Argument) error {
249
+ if !found && def.Required {
250
+ return fmt.Errorf("Argument '%s' is required", def.Name)
251
}
252
253
return nil