Skip to content

Commit e2af447

Browse files
committed
completion: support comma-separated value hints
Add a hint provider registry so that flag value hints can be populated at runtime without hardcoding values in struct tags. Flags using a completion:"csv:<name>" tag get comma-aware completion: already chosen values are filtered out and only the segment after the last comma is returned, matching bash COMP_WORDBREAKS behavior. Signed-off-by: Robin Jarry <robin@jarry.cc>
1 parent df5ede9 commit e2af447

1 file changed

Lines changed: 33 additions & 7 deletions

File tree

‎pkg/config/completion.go‎

Lines changed: 33 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -99,8 +99,24 @@ func bashComplete(app *kong.Kong) bool {
9999

100100
// complete flag values if we are positioned after a value-taking flag
101101
if prevFlag != nil && !prevFlag.IsBool() && !prevFlag.IsCounter() {
102-
for _, v := range flagValueHints(prevFlag) {
103-
add(v, "")
102+
hints, csv := flagValueHints(prevFlag)
103+
if csv && strings.Contains(prefix, ",") {
104+
lastComma := strings.LastIndex(prefix, ",")
105+
tail := prefix[lastComma+1:]
106+
chosen := make(map[string]bool)
107+
for _, v := range strings.Split(prefix[:lastComma], ",") {
108+
chosen[v] = true
109+
}
110+
prefix = tail
111+
for _, v := range hints {
112+
if !chosen[v] {
113+
add(v, "")
114+
}
115+
}
116+
} else {
117+
for _, v := range hints {
118+
add(v, "")
119+
}
104120
}
105121
goto print
106122
}
@@ -150,14 +166,24 @@ print:
150166
return true
151167
}
152168

153-
func flagValueHints(flag *kong.Flag) []string {
169+
var hintProviders = map[string][]string{}
170+
171+
func RegisterHints(name string, values []string) {
172+
hintProviders[name] = values
173+
}
174+
175+
func flagValueHints(flag *kong.Flag) (hints []string, csv bool) {
154176
if flag.Enum != "" {
155-
return strings.Split(flag.Enum, ",")
177+
return strings.Split(flag.Enum, ","), false
156178
}
157-
if c := flag.Tag.Get("completion"); c != "" {
158-
return strings.Split(c, ",")
179+
c := flag.Tag.Get("completion")
180+
if c == "" {
181+
return nil, false
159182
}
160-
return nil
183+
if name, ok := strings.CutPrefix(c, "csv:"); ok {
184+
return hintProviders[name], true
185+
}
186+
return strings.Split(c, ","), false
161187
}
162188

163189
func findFlag(node *kong.Node, name string) *kong.Flag {

0 commit comments

Comments
 (0)