-
Notifications
You must be signed in to change notification settings - Fork 0
/
option.go
80 lines (61 loc) · 1.57 KB
/
option.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
package autocomplete
import (
"fmt"
"sort"
"strconv"
"strings"
"github.com/spf13/cobra"
)
type Option struct {
Name string
Description string
}
func parseOptions(output string) (cobra.ShellCompDirective, []Option, error) {
lines := strings.Split(output, "\n")
if len(lines) < 2 {
return 0, nil, nil
}
var options = make([]Option, 0, len(lines)-1)
directive := cobra.ShellCompDirectiveDefault
// Loop over all the lines apart from the last two
for _, line := range lines[:len(lines)-1] {
if strings.HasPrefix(line, ":") {
directiveLine := lines[len(lines)-2]
if strings.HasPrefix(directiveLine, ":") {
directiveLine = directiveLine[1:]
value, err := strconv.ParseUint(strings.TrimSpace(directiveLine), 10, 64)
if err != nil {
directive = cobra.ShellCompDirective(value)
}
}
break
}
cmd, description, _ := strings.Cut(line, "\t")
if isShorthandFlag(cmd) {
continue
}
options = append(options, Option{
Name: escapeSpecialCharacters(cmd),
Description: description,
})
}
sort.Slice(options, func(i, j int) bool {
return options[i].Name < options[j].Name
})
return directive, options, nil
}
func escapeSpecialCharacters(val string) string {
for _, c := range []string{"\\", "\"", "$", "`", "!"} {
val = strings.ReplaceAll(val, c, "\\"+c)
}
if strings.ContainsAny(val, " #&*;<>?[]|~") {
val = fmt.Sprintf(`"%s"`, val)
}
return val
}
func isFlag(arg string) bool {
return strings.HasPrefix(arg, "-")
}
func isShorthandFlag(arg string) bool {
return isFlag(arg) && !strings.HasPrefix(arg, "--")
}