-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomplete.go
More file actions
516 lines (466 loc) · 15.3 KB
/
complete.go
File metadata and controls
516 lines (466 loc) · 15.3 KB
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
package cli
import (
"context"
"fmt"
"io"
"reflect"
"slices"
"strings"
)
// ShellCompDirective controls shell behavior after completing.
type ShellCompDirective int
const (
// ShellCompDirectiveDefault indicates default completion behavior.
ShellCompDirectiveDefault ShellCompDirective = 0
// ShellCompDirectiveNoSpace prevents adding a space after the completion.
ShellCompDirectiveNoSpace ShellCompDirective = 1 << iota
// ShellCompDirectiveNoFileComp disables file completion when no candidates match.
ShellCompDirectiveNoFileComp
// ShellCompDirectiveError indicates an error occurred during completion.
ShellCompDirectiveError
// ShellCompDirectiveFilterFileExt indicates completions are file extensions
// to filter by (e.g. ".yaml", ".json"). Shells will only show files matching
// these extensions.
ShellCompDirectiveFilterFileExt
// ShellCompDirectiveFilterDirs indicates only directories should be completed.
ShellCompDirectiveFilterDirs
)
// Completion represents a single shell completion candidate.
type Completion struct {
Value string // the completion value
Description string // optional description shown in shell
}
// CompletionResult holds completion candidates and metadata.
// Returned by Completer.Complete and FlagCompleter.CompleteFlag.
type CompletionResult struct {
Completions []Completion // completion candidates
ActiveHelp []string // contextual hints shown during completion
Directive ShellCompDirective // controls shell behavior
}
// Completions returns a CompletionResult with the given values.
// Use for simple completions without descriptions.
//
// return cli.Completions("foo", "bar", "baz")
func Completions(values ...string) CompletionResult {
comps := make([]Completion, len(values))
for i, v := range values {
comps[i] = Completion{Value: v}
}
return CompletionResult{
Completions: comps,
Directive: ShellCompDirectiveNoFileComp,
}
}
// CompletionsWithDesc returns a CompletionResult with the given completions.
// Use for completions with descriptions.
//
// return cli.CompletionsWithDesc(
// cli.Completion{Value: "us-east-1", Description: "N. Virginia"},
// cli.Completion{Value: "us-west-2", Description: "Oregon"},
// )
func CompletionsWithDesc(comps ...Completion) CompletionResult {
return CompletionResult{
Completions: comps,
Directive: ShellCompDirectiveNoFileComp,
}
}
// NoCompletions returns an empty CompletionResult that falls through to
// default completion behavior (e.g., file completion).
func NoCompletions() CompletionResult {
return CompletionResult{
Directive: ShellCompDirectiveDefault,
}
}
// WithDirective returns a copy of the result with the given directive.
func (r CompletionResult) WithDirective(d ShellCompDirective) CompletionResult {
r.Directive = d
return r
}
// WithActiveHelp returns a copy of the result with active help messages.
// Active help messages are displayed by the shell during completion to provide
// contextual guidance. Supported by bash (4.4+), zsh, and fish.
//
// return cli.Completions("dev", "staging", "prod").
// WithActiveHelp("Select deployment target")
func (r CompletionResult) WithActiveHelp(messages ...string) CompletionResult {
r.ActiveHelp = append(r.ActiveHelp, messages...)
return r
}
// FlagNameFor returns the flag name for a struct field, enabling type-safe
// flag references in CompleteFlag implementations. Pass a pointer to the
// command and a pointer to the specific field.
//
// func (c *DeployCmd) CompleteFlag(ctx context.Context, flag, value string) cli.CompletionResult {
// if flag == cli.FlagNameFor(c, &c.Region) {
// return cli.Completions("us-east-1", "us-west-2")
// }
// return cli.NoCompletions()
// }
//
// Returns empty string if the field is not found or has no flag tag.
func FlagNameFor[T any](cmd *T, fieldPtr any) string {
cmdVal := reflect.ValueOf(cmd).Elem()
cmdType := cmdVal.Type()
// Get the address the fieldPtr points to.
fieldVal := reflect.ValueOf(fieldPtr)
if fieldVal.Kind() != reflect.Ptr {
return ""
}
fieldAddr := fieldVal.Pointer()
// Find which field matches this address.
for i := range cmdType.NumField() {
if cmdVal.Field(i).CanAddr() && cmdVal.Field(i).Addr().Pointer() == fieldAddr {
field := cmdType.Field(i)
if flagName := field.Tag.Get("flag"); flagName != "" {
return flagName
}
// Fall back to kebab-case field name if no flag tag.
return camelToKebab(field.Name)
}
}
return ""
}
// activeHelpPrefix is prepended to active help messages. Shells recognize
// this prefix and display the message as guidance rather than a completion.
const activeHelpPrefix = "_activeHelp_ "
// RuntimeComplete generates completion candidates for the given args and writes
// them to w. Each candidate is one line, optionally followed by a tab and
// description. Active help messages are prefixed with "_activeHelp_ ".
// The last line is a directive in the format ":<int>".
func RuntimeComplete(ctx context.Context, root Commander, args []string, w io.Writer) {
result := computeCompletions(ctx, root, args)
// Output active help messages first.
for _, msg := range result.ActiveHelp {
fmt.Fprintln(w, activeHelpPrefix+msg) //nolint:errcheck // best-effort completion output
}
// Output completions.
for _, c := range result.Completions {
if c.Description != "" {
fmt.Fprintf(w, "%s\t%s\n", c.Value, c.Description) //nolint:errcheck // best-effort completion output
} else {
fmt.Fprintln(w, c.Value) //nolint:errcheck // best-effort completion output
}
}
fmt.Fprintf(w, ":%d\n", int(result.Directive)) //nolint:errcheck // best-effort completion output
}
// computeCompletions resolves the command chain and returns a CompletionResult.
func computeCompletions(ctx context.Context, root Commander, args []string) CompletionResult {
contextArgs, toComplete := splitCompletionArgs(args)
target := walkCommandTree(root, contextArgs)
// Try Completer interface first.
if result, ok := tryCompleterInterface(ctx, target, args, toComplete); ok {
return result
}
// Handle --flag=value completion (partial equals form).
if result, ok := completeFlagEqualsValue(ctx, target, toComplete); ok {
return result
}
// Complete flags if prefix starts with "-".
if strings.HasPrefix(toComplete, "-") {
return completeFlagNames(target, toComplete)
}
// Complete flag values if previous arg was a value flag.
if result, ok := completeFlagValue(ctx, target, contextArgs, toComplete); ok {
return result
}
// Complete subcommand names.
return completeSubcommandNames(target, toComplete)
}
func splitCompletionArgs(args []string) ([]string, string) {
if len(args) == 0 {
return nil, ""
}
return args[:len(args)-1], args[len(args)-1]
}
func walkCommandTree(root Commander, contextArgs []string) Commander {
target := root
remaining := contextArgs
for len(remaining) > 0 {
subs, err := allSubcommands(target)
if err != nil || len(subs) == 0 {
break
}
arg := remaining[0]
if strings.HasPrefix(arg, "-") {
fi := buildFlagIndex(target)
if consumed, ok := tryConsumeFlag(remaining, 0, fi); ok {
remaining = remaining[consumed:]
continue
}
remaining = remaining[1:]
continue
}
sub, err := findSubcommand(subs, arg, false, false)
if err != nil || sub == nil {
remaining = remaining[1:]
continue
}
target = sub
remaining = remaining[1:]
}
return target
}
func tryCompleterInterface(ctx context.Context, target Commander, args []string, toComplete string) (CompletionResult, bool) {
c, ok := target.(Completer)
if !ok {
return CompletionResult{}, false
}
result := c.Complete(ctx, args)
if len(result.Completions) == 0 && len(result.ActiveHelp) == 0 {
return CompletionResult{}, false
}
return filterResult(result, toComplete), true
}
func filterResult(result CompletionResult, toComplete string) CompletionResult {
filtered := filterCompletions(result.Completions, toComplete)
directive := result.Directive
if len(filtered) == 0 && result.Directive != ShellCompDirectiveError {
directive = ShellCompDirectiveDefault
}
return CompletionResult{
Completions: filtered,
ActiveHelp: result.ActiveHelp,
Directive: directive,
}
}
func completeFlagNames(target Commander, toComplete string) CompletionResult {
candidates := completeCommandFlags(target, toComplete)
directive := ShellCompDirectiveNoFileComp
if len(candidates) == 0 {
directive = ShellCompDirectiveDefault
}
return CompletionResult{Completions: candidates, Directive: directive}
}
// completeFlagEqualsValue handles completion for --flag=value form.
// Returns completions formatted as --flag=value to replace the entire token.
func completeFlagEqualsValue(ctx context.Context, target Commander, toComplete string) (CompletionResult, bool) {
if !strings.HasPrefix(toComplete, "-") {
return CompletionResult{}, false
}
eqIdx := strings.Index(toComplete, "=")
if eqIdx < 0 {
return CompletionResult{}, false
}
flagPart := toComplete[:eqIdx] // e.g., "--format"
valuePart := toComplete[eqIdx+1:] // e.g., "js"
flagName := lookupValueFlagName(target, flagPart)
if flagName == "" {
return CompletionResult{}, false
}
var candidates []Completion
// Try FlagCompleter interface.
if fc, ok := target.(FlagCompleter); ok {
result := fc.CompleteFlag(ctx, flagName, valuePart)
if len(result.Completions) > 0 || len(result.ActiveHelp) > 0 {
// Prefix completions with --flag= so they replace the whole token.
for _, c := range result.Completions {
if strings.HasPrefix(c.Value, valuePart) {
candidates = append(candidates, Completion{
Value: flagPart + "=" + c.Value,
Description: c.Description,
})
}
}
if len(candidates) > 0 {
return CompletionResult{
Completions: candidates,
ActiveHelp: result.ActiveHelp,
Directive: ShellCompDirectiveNoSpace,
}, true
}
}
}
// Try enum completion.
if enumVals := lookupFlagEnumByName(target, flagName); enumVals != "" {
vals := strings.Split(enumVals, ",")
for _, v := range vals {
if strings.HasPrefix(v, valuePart) {
candidates = append(candidates, Completion{Value: flagPart + "=" + v})
}
}
if len(candidates) > 0 {
return CompletionResult{
Completions: candidates,
Directive: ShellCompDirectiveNoSpace,
}, true
}
}
return CompletionResult{}, false
}
func completeFlagValue(ctx context.Context, target Commander, contextArgs []string, toComplete string) (CompletionResult, bool) {
if len(contextArgs) == 0 {
return CompletionResult{}, false
}
prev := contextArgs[len(contextArgs)-1]
flagName := lookupValueFlagName(target, prev)
if flagName == "" {
return CompletionResult{}, false
}
// Try FlagCompleter interface.
if fc, ok := target.(FlagCompleter); ok {
result := fc.CompleteFlag(ctx, flagName, toComplete)
if len(result.Completions) > 0 || len(result.ActiveHelp) > 0 {
return filterResult(result, toComplete), true
}
}
// Try enum completion.
if enumVals := lookupFlagEnum(target, prev); enumVals != "" {
vals := strings.Split(enumVals, ",")
filtered := filterStrings(vals, toComplete)
directive := ShellCompDirectiveNoFileComp
if len(filtered) == 0 {
directive = ShellCompDirectiveDefault
}
return CompletionResult{Completions: stringsToCompletions(filtered), Directive: directive}, true
}
return CompletionResult{}, false
}
func completeSubcommandNames(target Commander, toComplete string) CompletionResult {
subs, _ := allSubcommands(target) //nolint:errcheck // best-effort in completion
var candidates []Completion
for _, sub := range subs {
info := resolveInfo(sub)
if info.hidden {
continue
}
if strings.HasPrefix(info.name, toComplete) {
candidates = append(candidates, Completion{Value: info.name, Description: info.description})
}
for _, alias := range info.aliases {
if strings.HasPrefix(alias, toComplete) {
candidates = append(candidates, Completion{Value: alias, Description: info.description})
}
}
}
directive := ShellCompDirectiveNoFileComp
if len(candidates) == 0 {
directive = ShellCompDirectiveDefault
}
return CompletionResult{Completions: candidates, Directive: directive}
}
// completeCommandFlags returns flag completions matching prefix.
func completeCommandFlags(cmd Commander, prefix string) []Completion {
flags := ScanFlags(cmd)
var candidates []Completion
for i := range flags {
f := &flags[i]
if f.Hidden || f.Deprecated != "" {
continue
}
name := "--" + f.Name
if strings.HasPrefix(name, prefix) {
candidates = append(candidates, Completion{Value: name, Description: f.Help})
}
if f.Short != "" {
short := "-" + f.Short
if strings.HasPrefix(short, prefix) {
candidates = append(candidates, Completion{Value: short, Description: f.Help})
}
}
for _, alt := range f.Alt {
altName := "--" + alt
if strings.HasPrefix(altName, prefix) {
candidates = append(candidates, Completion{Value: altName, Description: f.Help})
}
}
if f.Negate {
neg := "--no-" + f.Name
if strings.HasPrefix(neg, prefix) {
candidates = append(candidates, Completion{Value: neg, Description: "Disable " + f.Name})
}
}
}
return candidates
}
// lookupValueFlagName returns the flag name (without dashes) if arg matches
// a non-bool, non-counter flag on cmd, or empty string if not found.
func lookupValueFlagName(cmd Commander, arg string) string {
if !strings.HasPrefix(arg, "-") {
return ""
}
flags := ScanFlags(cmd)
name := strings.TrimLeft(arg, "-")
for i := range flags {
f := &flags[i]
if f.Hidden || f.Deprecated != "" {
continue
}
if f.IsBool || f.IsCounter {
continue
}
if f.Name == name || f.Short == name || slices.Contains(f.Alt, name) {
return f.Name
}
}
return ""
}
// lookupFlagEnum returns the Enum string for a flag matching the given arg
// (e.g. "--format"), or empty if no match or no enum.
func lookupFlagEnum(cmd Commander, arg string) string {
if !strings.HasPrefix(arg, "-") {
return ""
}
flags := ScanFlags(cmd)
name := strings.TrimLeft(arg, "-")
for i := range flags {
f := &flags[i]
if f.Hidden || f.Deprecated != "" {
continue
}
if f.IsBool || f.IsCounter {
continue
}
if f.Enum == "" {
continue
}
if f.Name == name || f.Short == name || slices.Contains(f.Alt, name) {
return f.Enum
}
}
return ""
}
// lookupFlagEnumByName returns the Enum string for a flag by its name (without dashes).
func lookupFlagEnumByName(cmd Commander, flagName string) string {
flags := ScanFlags(cmd)
for i := range flags {
f := &flags[i]
if f.Name == flagName && f.Enum != "" {
return f.Enum
}
}
return ""
}
// filterCompletions filters candidates to those starting with prefix.
func filterCompletions(candidates []Completion, prefix string) []Completion {
if prefix == "" {
return candidates
}
var out []Completion
for _, c := range candidates {
if strings.HasPrefix(c.Value, prefix) {
out = append(out, c)
}
}
return out
}
// filterStrings filters string candidates to those starting with prefix.
func filterStrings(candidates []string, prefix string) []string {
if prefix == "" {
return candidates
}
var out []string
for _, c := range candidates {
if strings.HasPrefix(c, prefix) {
out = append(out, c)
}
}
return out
}
// stringsToCompletions converts strings to Completion values.
func stringsToCompletions(vals []string) []Completion {
comps := make([]Completion, len(vals))
for i, v := range vals {
comps[i] = Completion{Value: v}
}
return comps
}