-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathargs.go
69 lines (63 loc) · 1.8 KB
/
args.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
package args
import (
"github.com/stackitcloud/stackit-cli/internal/pkg/errors"
"github.com/spf13/cobra"
)
func NoArgs(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return nil
}
return &errors.InputUnknownError{
ProvidedInput: args[0],
Cmd: cmd,
}
}
// SingleArg checks if only one non-empty argument was provided and validates it
// using the validate function. It returns an error if none or multiple arguments
// are provided, or if the argument is invalid.
// For no validation, you can pass a nil validate function
func SingleArg(argName string, validate func(value string) error) cobra.PositionalArgs {
return func(cmd *cobra.Command, args []string) error {
if len(args) != 1 || args[0] == "" {
return &errors.SingleArgExpectedError{
Cmd: cmd,
Expected: argName,
Count: len(args),
}
}
if validate != nil {
err := validate(args[0])
if err != nil {
return &errors.ArgValidationError{
Arg: argName,
Details: err.Error(),
}
}
}
return nil
}
}
// SingleOptionalArg checks if one or no arguments were provided and validates it if provided
// using the validate function. It returns an error if more than one argument is provided, or if
// the argument is invalid. For no validation, you can pass a nil validate function
func SingleOptionalArg(argName string, validate func(value string) error) cobra.PositionalArgs {
return func(cmd *cobra.Command, args []string) error {
if len(args) > 1 {
return &errors.SingleOptionalArgExpectedError{
Cmd: cmd,
Expected: argName,
Count: len(args),
}
}
if len(args) == 1 && validate != nil {
err := validate(args[0])
if err != nil {
return &errors.ArgValidationError{
Arg: argName,
Details: err.Error(),
}
}
}
return nil
}
}