/
commando.go
382 lines (346 loc) · 9.25 KB
/
commando.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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
/*
* Copyright (C) 1999-2019 Alibaba Group Holding Limited
*/
package openapi
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
"github.com/aliyun/aliyun-cli/cli"
"github.com/aliyun/aliyun-cli/config"
"github.com/aliyun/aliyun-cli/i18n"
"github.com/aliyun/aliyun-cli/meta"
"bytes"
"encoding/json"
"fmt"
"io"
"strings"
)
// main entrance of aliyun cli
type Commando struct {
profile config.Profile
library *Library
}
var hookdo = func(fn func()(*responses.CommonResponse, error)) func()(*responses.CommonResponse, error){
return fn
}
func NewCommando(w io.Writer, profile config.Profile) *Commando {
r := &Commando{
profile: profile,
}
r.library = NewLibrary(w, profile.Language) //TODO: load from local repository
return r
}
func (c *Commando) InitWithCommand(cmd *cli.Command) {
cmd.Run = c.main
cmd.Help = c.help
cmd.AutoComplete = c.complete
}
//
func (c *Commando) main(ctx *cli.Context, args []string) error {
//
// aliyun
if len(args) == 0 {
c.printUsage(ctx)
return nil
}
// update current `Profile` with flags
var err error
c.profile, err = config.LoadProfileWithContext(ctx)
if err != nil {
return cli.NewErrorWithTip(err, "Configuration failed, use `aliyun configure` to configure it")
}
err = c.profile.Validate()
if err != nil {
return cli.NewErrorWithTip(err, "Configuration failed, use `aliyun configure` to configure it.")
}
i18n.SetLanguage(c.profile.Language)
// process following commands:
// aliyun <productCode>
// aliyun <productCode> <method> --param1 value1
// aliyun <productCode> GET <path>
productName := args[0]
if len(args) == 1 {
// aliyun <productCode>
// TODO: aliyun pluginName ...
return c.library.PrintProductUsage(productName, true)
} else if len(args) == 2 {
// rpc or restful call
// aliyun <productCode> <method> --param1 value1
product, _ := c.library.GetProduct(args[0])
if product.ApiStyle == "restful" {
api, _ := c.library.GetApi(product.Code, product.Version, args[1])
return c.processInvoke(ctx, productName, api.Method, api.PathPattern)
}
return c.processInvoke(ctx, productName, args[1], "")
} else if len(args) == 3 {
// restful call
// aliyun <productCode> {GET|PUT|POST|DELETE} <path> --
return c.processInvoke(ctx, productName, args[1], args[2])
} else {
return cli.NewErrorWithTip(fmt.Errorf("too many arguments"),
"Use `aliyun --help` to show usage")
}
}
func (c *Commando) processInvoke(ctx *cli.Context, productCode string, apiOrMethod string, path string) error {
// create specific invoker
invoker, err := c.createInvoker(ctx, productCode, apiOrMethod, path)
if err != nil {
return err
}
err = invoker.Prepare(ctx)
if err != nil {
return err
}
// process --dryrun
if DryRunFlag(ctx.Flags()).IsAssigned() {
invoker.getRequest().TransToAcsRequest()
invoker.getClient().BuildRequestWithSigner(invoker.getRequest(), nil)
cli.Printf(ctx.Writer(), "Skip invoke in dry-run mode, request is:\n------------------------------------\n%s\n",
invoker.getRequest().String())
return nil
}
// if invoke with helper
out, err, ok := c.invokeWithHelper(invoker)
// cli.Printf("invoker %v %v \n", invoker, reflect.TypeOf(invoker))
if ok {
if err != nil { // call with helper failed
return err
}
} else {
resp, err := hookdo(invoker.Call)()
if err != nil {
// if unmarshal failed,
if !strings.Contains(strings.ToLower(err.Error()), "unmarshal") {
return err
}
}
out = resp.GetHttpContentString()
}
// if `--quiet` assigned. do not print anything
if QuietFlag(ctx.Flags()).IsAssigned() {
return nil
}
// process `--output ...`
if filter := GetOutputFilter(ctx); filter != nil {
out, err = filter.FilterOutput(out)
if err != nil {
return err
}
}
out = FormatJson(out)
cli.Println(ctx.Writer(), out)
return nil
}
func FormatJson(content string) string {
var buf bytes.Buffer
err := json.Indent(&buf, []byte(content), "", "\t")
if err == nil {
content = buf.String()
}
return content
}
// invoke with helper
func (c *Commando) invokeWithHelper(invoker Invoker) (resp string, err error, ok bool) {
if pager := GetPager(); pager != nil {
// cli.Printf("call with pager")
resp, err = pager.CallWith(invoker)
ok = true
return
}
if waiter := GetWaiter(); waiter != nil {
// cli.Printf("call with waiter")
resp, err = waiter.CallWith(invoker)
ok = true
return
}
ok = false
return
}
//
// create invoker for specific case
// rpc: RpcInvoker, ForceRpcInvoker
// restful: RestfulInvoker
func (c *Commando) createInvoker(ctx *cli.Context, productCode string, apiOrMethod string, path string) (Invoker, error) {
force := ForceFlag(ctx.Flags()).IsAssigned()
basicInvoker := NewBasicInvoker(&c.profile)
//
// get product info
if product, ok := c.library.GetProduct(productCode); ok {
err := basicInvoker.Init(ctx, &product)
if err != nil {
return nil, err
}
if strings.ToLower(product.ApiStyle) == "rpc" {
//
// Rpc call
if path != "" {
return nil, cli.NewErrorWithTip(fmt.Errorf("invalid argument %s", path),
"Use `aliyun help %s` see more information.", product.GetLowerCode())
}
if force {
return &ForceRpcInvoker{
basicInvoker,
apiOrMethod,
}, nil
} else {
if api, ok := c.library.GetApi(product.Code, product.Version, apiOrMethod); ok {
return &RpcInvoker{
basicInvoker,
&api,
}, nil
} else {
return nil, &InvalidApiError{apiOrMethod, &product}
}
}
} else {
//
// Restful Call
// aliyun cs GET /clusters
// aliyun cs /clusters --roa GET
ok, method, path, err := checkRestfulMethod(ctx, apiOrMethod, path)
if err != nil {
return nil, err
}
if !ok {
return nil, cli.NewErrorWithTip(fmt.Errorf("product '%s' need restful call", product.GetLowerCode()),
"Use `aliyun %s {GET|PUT|POST|DELETE} <path> ...`", product.GetLowerCode())
}
return &RestfulInvoker{
basicInvoker,
method,
path,
force,
}, nil
//if err != nil {
// ctx.Command().PrintFailed(fmt.Errorf("call restful %s%s.%s faild %v", product.Code, path, method, err), "")
// return nil
//}
}
} else {
if !force {
return nil, &InvalidProductError{Code: productCode, library: c.library}
}
//
// force call on unknown product, use temporary product info
product = meta.Product{
Code: productCode,
}
err := basicInvoker.Init(ctx, &product)
if err != nil {
return nil, err
}
//
// Restful Call
// aliyun cs GET /clusters
// aliyun cs /clusters --roa GET
ok, method, path, err := checkRestfulMethod(ctx, apiOrMethod, path)
if err != nil {
return nil, err
}
if ok {
return &RestfulInvoker{
basicInvoker,
method,
path,
force,
}, nil
// return invoker, nil
// c.InvokeRestful(ctx, &product, method, path)
} else {
return &ForceRpcInvoker{
basicInvoker,
apiOrMethod,
}, nil
// c.InvokeRpcForce(ctx, &product, apiOrMethod)
}
}
}
//
func (c *Commando) help(ctx *cli.Context, args []string) error {
cmd := ctx.Command()
//if err != nil {
// cli.Errorf("ERROR: %s\n", err.Error())
// printUsage(ctx.Command(), nil)
// } else {
if len(args) == 0 {
cmd.PrintHead(ctx)
cmd.PrintUsage(ctx)
cmd.PrintFlags(ctx)
cmd.PrintSample(ctx)
c.library.PrintProducts()
cmd.PrintTail(ctx)
return nil
} else if len(args) == 1 {
cmd.PrintHead(ctx)
return c.library.PrintProductUsage(args[0], true)
// c.PrintFlags() TODO add later
} else if len(args) == 2 {
cmd.PrintHead(ctx)
return c.library.PrintApiUsage(args[0], args[1])
// c.PrintFlags() TODO add later
} else {
return fmt.Errorf("too many arguments: %d", len(args))
}
}
//
func (c *Commando) complete(ctx *cli.Context, args []string) []string {
w := ctx.Writer()
r := make([]string, 0)
//
// aliyun
if len(args) == 0 {
ctx.Command().ExecuteComplete(ctx, args)
for _, p := range c.library.GetProducts() {
if !strings.HasPrefix(p.GetLowerCode(), ctx.Completion().Current) {
continue
}
cli.PrintfWithColor(w, cli.ProductListColor(), "%s\n", p.GetLowerCode())
}
return r
}
product, ok := c.library.GetProduct(args[0])
if !ok {
return r
}
if product.ApiStyle == "rpc" {
if len(args) == 1 {
for _, name := range product.ApiNames {
if !strings.HasPrefix(name, ctx.Completion().Current) {
continue
}
cli.PrintfWithColor(w, cli.APIListColor(), "%s\n", name)
}
return r
}
api, ok := c.library.GetApi(product.Code, product.Version, args[1])
if !ok {
return r
}
api.ForeachParameters(func(s string, p meta.Parameter) {
if strings.HasPrefix("--"+s, ctx.Completion().Current) && !p.Hidden {
cli.Printf(ctx.Writer(), "--%s\n", s)
}
})
} else if product.ApiStyle == "restful" {
if len(args) == 1 {
cli.PrintfWithColor(w, cli.APIListColor(), "GET\n")
cli.PrintfWithColor(w, cli.APIListColor(), "POST\n")
cli.PrintfWithColor(w, cli.APIListColor(), "DELETE\n")
cli.PrintfWithColor(w, cli.APIListColor(), "PUT\n")
return r
}
}
return r
}
func (c *Commando) printUsage(ctx *cli.Context) {
cmd := ctx.Command()
cmd.PrintHead(ctx)
cmd.PrintUsage(ctx)
cmd.PrintSubCommands(ctx)
cmd.PrintFlags(ctx)
cmd.PrintSample(ctx)
//if configError != nil {
// cli.Printf("Configuration Invailed: %s\n", configError)
// cli.Printf("Run `aliyun configure` first:\n %s\n", configureCommand.Usage)
//}
cmd.PrintTail(ctx)
}