-
Notifications
You must be signed in to change notification settings - Fork 2
/
comp_arguments.go
79 lines (65 loc) · 1.77 KB
/
comp_arguments.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
package mcli
import (
"context"
"flag"
"strings"
)
type CompletionItem struct {
Value string
Description string
}
// ArgCompletionFunc is a function to do completion for flag value or positional argument.
type ArgCompletionFunc func(ctx ArgCompletionContext) []CompletionItem
// ArgCompletionContext provides essential information to do suggestion
// for flag value and positional argument completion.
type ArgCompletionContext interface {
context.Context
GlobalFlags() any
CommandArgs() any
FlagSet() *flag.FlagSet
ArgPrefix() string
}
func (p *App) newArgCompletionContext() ArgCompletionContext {
return &compContextImpl{
Context: context.Background(),
app: p,
}
}
type compContextImpl struct {
context.Context
app *App
}
func (c *compContextImpl) GlobalFlags() any {
return c.app.globalFlags
}
func (c *compContextImpl) CommandArgs() any {
return c.app.completionCtx.parsedArgs
}
func (c *compContextImpl) FlagSet() *flag.FlagSet {
return c.app.getFlagSet()
}
func (c *compContextImpl) ArgPrefix() string {
return c.app.completionCtx.prefixWord
}
// WithArgCompFuncs specifies completion functions to complete flag values
// or positional arguments.
// Key of funcMap should be a flag name in form "-flag" or a positional arg name "arg1".
func WithArgCompFuncs(funcMap map[string]ArgCompletionFunc) ParseOpt {
copyMap := make(map[string]ArgCompletionFunc)
for name, x := range funcMap {
name = normalizeCompFlagName(name)
copyMap[name] = x
}
return ParseOpt{f: func(options *parseOptions) {
options.argCompFuncs = copyMap
}}
}
func normalizeCompFlagName(s string) string {
if strings.HasPrefix(s, "-") {
s = "-" + strings.TrimLeft(s, "-")
}
return strings.TrimSpace(s)
}
func cleanFlagName(s string) string {
return strings.TrimLeft(s, "-")
}