-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathcompleter.go
437 lines (401 loc) · 11.4 KB
/
completer.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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package cli
import (
"fmt"
"sort"
"strings"
"unicode"
"github.com/apache/cloudstack-cloudmonkey/cmd"
"github.com/apache/cloudstack-cloudmonkey/config"
)
func buildAPICacheMap(apiMap map[string][]*config.API) map[string][]*config.API {
for _, cmd := range cmd.AllCommands() {
verb := cmd.Name
if cmd.SubCommands != nil && len(cmd.SubCommands) > 0 {
for command, opts := range cmd.SubCommands {
var args []*config.APIArg
options := opts
if command == "profile" {
options = config.GetProfiles()
}
for _, opt := range options {
args = append(args, &config.APIArg{
Name: opt,
})
}
apiMap[verb] = append(apiMap[verb], &config.API{
Name: command,
Verb: verb,
Noun: command,
Args: args,
})
}
} else {
dummyAPI := &config.API{
Name: "",
Verb: verb,
}
apiMap[verb] = append(apiMap[verb], dummyAPI)
}
}
return apiMap
}
func trimSpaceLeft(in []rune) []rune {
firstIndex := len(in)
for i, r := range in {
if unicode.IsSpace(r) == false {
firstIndex = i
break
}
}
return in[firstIndex:]
}
func equal(a, b []rune) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if a[i] != b[i] {
return false
}
}
return true
}
func hasPrefix(r, prefix []rune) bool {
if len(r) < len(prefix) {
return false
}
return equal(r[:len(prefix)], prefix)
}
func inArray(s string, array []string) bool {
for _, item := range array {
if s == item {
return true
}
}
return false
}
func lastString(array []string) string {
return array[len(array)-1]
}
type argOption struct {
Value string
Detail string
}
func buildArgOptions(response map[string]interface{}, hasID bool) []argOption {
argOptions := []argOption{}
for _, v := range response {
switch obj := v.(type) {
case []interface{}:
if obj == nil {
break
}
for _, item := range obj {
resource, ok := item.(map[string]interface{})
if !ok {
continue
}
var id, name, detail string
if resource["id"] != nil {
id = resource["id"].(string)
}
if resource["name"] != nil {
name = resource["name"].(string)
} else if resource["username"] != nil {
name = resource["username"].(string)
} else if resource["hypervisor"] != nil && resource["hypervisorversion"] != nil {
name = fmt.Sprintf("%s %s", resource["hypervisor"].(string), resource["hypervisorversion"].(string))
if resource["osdisplayname"] != nil {
name = fmt.Sprintf("%s; %s", resource["osdisplayname"].(string), name)
}
}
if resource["displaytext"] != nil {
detail = resource["displaytext"].(string)
}
if len(detail) == 0 && resource["description"] != nil {
detail = resource["description"].(string)
}
if len(detail) == 0 && resource["ipaddress"] != nil {
detail = resource["ipaddress"].(string)
}
var opt argOption
if hasID {
opt.Value = id
opt.Detail = name
if len(name) == 0 {
opt.Detail = detail
}
} else {
opt.Value = name
opt.Detail = detail
if len(name) == 0 {
opt.Value = detail
}
}
argOptions = append(argOptions, opt)
}
break
}
}
return argOptions
}
func doInternal(line []rune, pos int, lineLen int, argName []rune) (newLine [][]rune, offset int) {
offset = lineLen
if lineLen >= len(argName) {
if hasPrefix(line, argName) {
if lineLen == len(argName) {
newLine = append(newLine, []rune{' '})
} else {
newLine = append(newLine, argName)
}
offset = offset - len(argName) - 1
}
} else {
if hasPrefix(argName, line) {
newLine = append(newLine, argName[offset:])
}
}
return
}
func findAPI(apiMap map[string][]*config.API, relatedNoun string) *config.API {
var autocompleteAPI *config.API
for _, listAPI := range apiMap["list"] {
if relatedNoun == listAPI.Noun {
autocompleteAPI = listAPI
break
}
}
return autocompleteAPI
}
func findAutocompleteAPI(arg *config.APIArg, apiFound *config.API, apiMap map[string][]*config.API) *config.API {
if arg.Type == "map" {
return nil
}
var autocompleteAPI *config.API
argName := strings.Replace(arg.Name, "=", "", -1)
relatedNoun := argName
switch {
case argName == "id" || argName == "ids":
// Heuristic: user is trying to autocomplete for id/ids arg for a list API
relatedNoun = apiFound.Noun
if apiFound.Verb != "list" {
relatedNoun += "s"
}
case argName == "account":
// Heuristic: user is trying to autocomplete for accounts
relatedNoun = "accounts"
case argName == "ipaddressid":
// Heuristic: user is trying to autocomplete for ip addresses
relatedNoun = "publicipaddresses"
case argName == "storageid":
relatedNoun = "storagepools"
case argName == "associatednetworkid":
relatedNoun = "networks"
default:
// Heuristic: autocomplete for the arg for which a list<Arg without id/ids>s API exists
// For example, for zoneid arg, listZones API exists
cutIdx := len(argName)
if strings.HasSuffix(argName, "id") {
cutIdx -= 2
} else if strings.HasSuffix(argName, "ids") {
cutIdx -= 3
} else {
}
relatedNoun = argName[:cutIdx] + "s"
}
config.Debug("Possible related noun for the arg: ", relatedNoun, " and type: ", arg.Type)
autocompleteAPI = findAPI(apiMap, relatedNoun)
if autocompleteAPI == nil {
if strings.Contains(strings.ToLower(relatedNoun), "storage") {
relatedNoun = "storagepools"
autocompleteAPI = findAPI(apiMap, relatedNoun)
}
}
if autocompleteAPI != nil {
config.Debug("Autocomplete: API found using heuristics: ", autocompleteAPI.Name)
}
if strings.HasSuffix(relatedNoun, "s") {
relatedNoun = relatedNoun[:len(relatedNoun)-1]
}
// Heuristic: find any list API that contains the arg name
if autocompleteAPI == nil {
config.Debug("Finding possible API that have: ", argName, " related APIs: ", arg.Related)
possibleAPIs := []*config.API{}
for _, listAPI := range apiMap["list"] {
if strings.Contains(listAPI.Noun, argName) {
config.Debug("Found possible API: ", listAPI.Name)
possibleAPIs = append(possibleAPIs, listAPI)
}
}
if len(possibleAPIs) == 1 {
autocompleteAPI = possibleAPIs[0]
}
}
return autocompleteAPI
}
type autoCompleter struct {
Config *config.Config
}
func (t *autoCompleter) Do(line []rune, pos int) (options [][]rune, offset int) {
apiMap := buildAPICacheMap(t.Config.GetAPIVerbMap())
var verbs []string
for verb := range apiMap {
verbs = append(verbs, verb)
sort.Slice(apiMap[verb], func(i, j int) bool {
return apiMap[verb][i].Name < apiMap[verb][j].Name
})
}
sort.Strings(verbs)
line = trimSpaceLeft(line[:pos])
// Auto-complete verb
var verbFound string
for _, verb := range verbs {
search := verb + " "
if !hasPrefix(line, []rune(search)) {
sLine, sOffset := doInternal(line, pos, len(line), []rune(search))
options = append(options, sLine...)
offset = sOffset
} else {
verbFound = verb
break
}
}
if len(verbFound) == 0 {
return
}
// Auto-complete noun
var nounFound string
line = trimSpaceLeft(line[len(verbFound):])
for _, api := range apiMap[verbFound] {
search := api.Noun + " "
if !hasPrefix(line, []rune(search)) {
sLine, sOffset := doInternal(line, pos, len(line), []rune(search))
options = append(options, sLine...)
offset = sOffset
} else {
nounFound = api.Noun
break
}
}
if len(nounFound) == 0 {
return
}
// Find API
var apiFound *config.API
for _, api := range apiMap[verbFound] {
if api.Noun == nounFound {
apiFound = api
break
}
}
if apiFound == nil {
return
}
// Auto-complete API arg
splitLine := strings.Split(string(line), " ")
line = trimSpaceLeft([]rune(splitLine[len(splitLine)-1]))
for _, arg := range apiFound.Args {
search := arg.Name
if !hasPrefix(line, []rune(search)) {
sLine, sOffset := doInternal(line, pos, len(line), []rune(search))
options = append(options, sLine...)
offset = sOffset
} else {
words := strings.Split(string(line), "=")
argInput := lastString(words)
if arg.Type == "boolean" {
for _, search := range []string{"true ", "false "} {
offset = 0
if strings.HasPrefix(search, argInput) {
options = append(options, []rune(search[len(argInput):]))
offset = len(argInput)
}
}
return
}
if arg.Type == config.FAKE && arg.Name == "filter=" {
offset = 0
filterInputs := strings.Split(strings.Replace(argInput, ",", ",|", -1), "|")
lastFilterInput := lastString(filterInputs)
for _, key := range apiFound.ResponseKeys {
if inArray(key, filterInputs) {
continue
}
if strings.HasPrefix(key, lastFilterInput) {
options = append(options, []rune(key[len(lastFilterInput):]))
offset = len(lastFilterInput)
}
}
return
}
autocompleteAPI := findAutocompleteAPI(arg, apiFound, apiMap)
if autocompleteAPI == nil {
return nil, 0
}
completeArgs := t.Config.Core.AutoComplete
autocompleteAPIArgs := []string{}
argOptions := []argOption{}
if completeArgs {
autocompleteAPIArgs = []string{"listall=true"}
if autocompleteAPI.Noun == "templates" {
autocompleteAPIArgs = append(autocompleteAPIArgs, "templatefilter=executable")
}
if apiFound.Name != "provisionCertificate" && autocompleteAPI.Name == "listHosts" {
autocompleteAPIArgs = append(autocompleteAPIArgs, "type=Routing")
} else if apiFound.Name == "migrateSystemVm" {
autocompleteAPI.Name = "listSystemVms"
} else if apiFound.Name == "associateIpAddress" {
autocompleteAPIArgs = append(autocompleteAPIArgs, "state=Free")
}
spinner := t.Config.StartSpinner("fetching options, please wait...")
request := cmd.NewRequest(nil, completer.Config, nil)
response, _ := cmd.NewAPIRequest(request, autocompleteAPI.Name, autocompleteAPIArgs, false)
t.Config.StopSpinner(spinner)
hasID := strings.HasSuffix(arg.Name, "id=") || strings.HasSuffix(arg.Name, "ids=")
argOptions = buildArgOptions(response, hasID)
}
filteredOptions := []argOption{}
if len(argOptions) > 0 {
sort.Slice(argOptions, func(i, j int) bool {
return argOptions[i].Value < argOptions[j].Value
})
for _, item := range argOptions {
if strings.HasPrefix(item.Value, argInput) {
filteredOptions = append(filteredOptions, item)
}
}
}
offset = 0
if len(filteredOptions) == 0 {
options = [][]rune{[]rune("")}
}
for _, item := range filteredOptions {
option := item.Value + " "
if len(filteredOptions) > 1 && len(item.Detail) > 0 {
option += fmt.Sprintf("(%v)", item.Detail)
}
if strings.HasPrefix(option, argInput) {
options = append(options, []rune(option[len(argInput):]))
offset = len(argInput)
}
}
return
}
}
return options, offset
}