/
cobra_utils.go
277 lines (235 loc) · 8 KB
/
cobra_utils.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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
package core
import (
"context"
"errors"
"fmt"
"reflect"
"strings"
"github.com/scaleway/scaleway-cli/v2/internal/args"
"github.com/scaleway/scaleway-cli/v2/internal/sentry"
"github.com/spf13/cobra"
)
// cobraRun returns a cobraRun command that wrap a CommandRunner function.
func cobraRun(ctx context.Context, cmd *Command) func(*cobra.Command, []string) error {
return func(cobraCmd *cobra.Command, rawArgsStr []string) error {
rawArgs := args.RawArgs(rawArgsStr)
meta := extractMeta(ctx)
meta.command = cmd
sentry.AddCommandContext(cmd.GetCommandLine("scw"))
// If command requires authentication and the client was not directly provided in the bootstrap config, we create a new client and overwrite the existing one
if !cmd.AllowAnonymousClient && !meta.isClientFromBootstrapConfig {
client, err := meta.Platform.CreateClient(meta.httpClient, ExtractConfigPath(ctx), ExtractProfileName(ctx))
if err != nil {
return createClientError(err)
}
meta.Client = client
}
// If command has no Run method there is nothing to do.
if cmd.Run == nil {
return nil
}
// Apply default values on missing args.
rawArgs = ApplyDefaultValues(ctx, cmd.ArgSpecs, rawArgs)
positionalArgSpec := cmd.ArgSpecs.GetPositionalArg()
// If this command has no positional argument we execute the run
if positionalArgSpec == nil {
data, err := run(ctx, cobraCmd, cmd, rawArgs)
if err != nil {
return err
}
meta.result = data
return nil
}
positionalArgs := rawArgs.GetPositionalArgs()
// Return an error if a positional argument was provide using `key=value` syntax.
value, exist := rawArgs.Get(positionalArgSpec.Name)
if exist {
otherArgs := rawArgs.Remove(positionalArgSpec.Name)
return &CliError{
Err: fmt.Errorf("a positional argument is required for this command"),
Hint: positionalArgHint(meta.BinaryName, cmd, value, otherArgs, len(positionalArgs) > 0),
}
}
// If no positional arguments were provided, return an error
if len(positionalArgs) == 0 {
return &CliError{
Err: fmt.Errorf("a positional argument is required for this command"),
Hint: positionalArgHint(meta.BinaryName, cmd, "<"+positionalArgSpec.Name+">", rawArgs, false),
}
}
results := MultiResults(nil)
rawArgs = rawArgs.RemoveAllPositional()
if cmd.AcceptMultiplePositionalArgs {
argNameWithIndex := fmt.Sprintf("%s.%d", positionalArgSpec.Name, 0)
rawArgsWithPositional := rawArgs.Add(argNameWithIndex, positionalArgs[0])
for i := 1; i < len(positionalArgs); i++ {
argNameWithIndex = fmt.Sprintf("%s.%d", positionalArgSpec.Name, i)
rawArgsWithPositional = rawArgsWithPositional.Add(argNameWithIndex, positionalArgs[i])
}
result, err := run(ctx, cobraCmd, cmd, rawArgsWithPositional)
if err != nil {
return err
}
results = append(results, result)
} else {
for _, positionalArg := range positionalArgs {
rawArgsWithPositional := rawArgs.Add(positionalArgSpec.Name, positionalArg)
result, err := run(ctx, cobraCmd, cmd, rawArgsWithPositional)
if err != nil {
return err
}
results = append(results, result)
}
}
// If only one positional parameter was provided we return the result directly instead of
// an array of results
if len(results) == 1 {
meta.result = results[0]
} else {
meta.result = results
}
return nil
}
}
func run(ctx context.Context, cobraCmd *cobra.Command, cmd *Command, rawArgs []string) (interface{}, error) {
var err error
// create a new Args interface{}
// unmarshalled arguments will be store in this interface
cmdArgs := reflect.New(cmd.ArgsType).Interface()
sentry.AddArgumentsContext(args.SplitRaw(rawArgs))
// Unmarshal args.
// After that we are done working with rawArgs
// and will be working with cmdArgs.
err = args.UnmarshalStruct(rawArgs, cmdArgs)
if err != nil {
if unmarshalError, ok := err.(*args.UnmarshalArgError); ok {
return nil, handleUnmarshalErrors(cmd, unmarshalError)
}
return nil, err
}
// Load args file imports.
err = loadArgsFileContent(cmd, cmdArgs)
if err != nil {
return nil, err
}
// PreValidate hook.
if cmd.PreValidateFunc != nil {
err = cmd.PreValidateFunc(ctx, cmdArgs)
if err != nil {
return nil, err
}
}
// Validate
validateFunc := DefaultCommandValidateFunc()
if cmd.ValidateFunc != nil {
validateFunc = cmd.ValidateFunc
}
err = validateFunc(ctx, cmd, cmdArgs, rawArgs)
if err != nil {
return nil, err
}
webFlag, err := cobraCmd.PersistentFlags().GetBool("web")
if err == nil && webFlag {
return runWeb(cmd, cmdArgs)
}
// execute the command
interceptor := CombineCommandInterceptor(
sdkStdErrorInterceptor,
sdkStdTypeInterceptor,
cmd.Interceptor,
)
data, err := interceptor(ctx, cmdArgs, func(ctx context.Context, argsI interface{}) (i interface{}, err error) {
return cmd.Run(ctx, argsI)
})
if err != nil {
return nil, err
}
waitFlag, err := cobraCmd.PersistentFlags().GetBool("wait")
if err == nil && cmd.WaitFunc != nil && waitFlag {
data, err = cmd.WaitFunc(ctx, cmdArgs, data)
if err != nil {
return nil, err
}
}
return data, nil
}
// positionalArgHint formats the positional argument error hint.
func positionalArgHint(binaryName string, cmd *Command, hintValue string, otherArgs []string, positionalArgumentFound bool) string {
suggestedArgs := []string{}
// If no positional argument exists, suggest one.
if !positionalArgumentFound {
suggestedArgs = append(suggestedArgs, hintValue)
}
// Suggest to use the other arguments.
suggestedArgs = append(suggestedArgs, otherArgs...)
suggestedCommand := append([]string{cmd.GetCommandLine(binaryName)}, suggestedArgs...)
return "Try running: " + strings.Join(suggestedCommand, " ")
}
func handleUnmarshalErrors(cmd *Command, unmarshalErr *args.UnmarshalArgError) error {
wrappedErr := errors.Unwrap(unmarshalErr)
switch e := wrappedErr.(type) {
case *args.CannotUnmarshalError:
switch e.Err.(type) {
case *args.CannotParseBoolError:
return &CliError{
Err: fmt.Errorf(""),
Message: fmt.Sprintf("invalid value for '%s' argument: invalid boolean value", unmarshalErr.ArgName),
Hint: "Possible values: true, false",
}
case *args.CannotParseDateError:
dateErr := e.Err.(*args.CannotParseDateError)
return &CliError{
Err: fmt.Errorf("date parsing error: %s", dateErr.ArgValue),
Message: fmt.Sprintf("could not parse %s as either an absolute time (RFC3339) nor a relative time (+/-)RFC3339", dateErr.ArgValue),
Details: fmt.Sprintf(`Absolute time error: %s
Relative time error: %s
`, dateErr.AbsoluteTimeParseError, dateErr.RelativeTimeParseError),
Hint: "Run `scw help date` to learn more about date parsing",
}
default:
return &CliError{
Err: fmt.Errorf("invalid value for '%s' argument: %s", unmarshalErr.ArgName, e.Err),
}
}
case *args.InvalidArgNameError:
argNames := []string(nil)
nonDeprecatedArgs := cmd.ArgSpecs.GetDeprecated(false)
for _, argSpec := range nonDeprecatedArgs {
argNames = append(argNames, argSpec.Name)
}
return &CliError{
Err: fmt.Errorf("invalid argument '%s': %s", unmarshalErr.ArgName, e.Error()),
Hint: fmt.Sprintf("Valid arguments are: %s", strings.Join(argNames, ", ")),
}
case *args.UnknownArgError:
argNames := []string(nil)
nonDeprecatedArgs := cmd.ArgSpecs.GetDeprecated(false)
for _, argSpec := range nonDeprecatedArgs {
argNames = append(argNames, argSpec.Name)
}
return &CliError{
Err: fmt.Errorf("unknown argument '%s'", unmarshalErr.ArgName),
Hint: fmt.Sprintf("Valid arguments are: %s", strings.Join(argNames, ", ")),
}
default:
return &CliError{Err: unmarshalErr}
}
}
func cobraRunHelp(cmd *Command) func(cmd *cobra.Command, args []string) error {
return func(cobraCmd *cobra.Command, _ []string) error {
webFlag, err := cobraCmd.PersistentFlags().GetBool("web")
if err == nil && webFlag {
out, err := runWeb(cmd, nil)
if err != nil {
return err
}
cobraCmd.Println(out)
return nil
}
err = cobraCmd.Help()
if err != nil {
return err
}
return &CliError{Empty: true, Code: 1}
}
}