-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcobra.go
55 lines (44 loc) · 1.19 KB
/
cobra.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
package completion
import (
"regexp"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
// Cobra adapter for completion
func Cobra(cmd *cobra.Command) ICommand {
var cobraCommandConverterWithParent func(cmd *cobra.Command, parent *command) *command
cobraCommandConverterWithParent = func(cmd *cobra.Command, parent *command) *command {
use := strings.Split(cmd.Use, " ")
var command = command{
Name: use[0],
Description: cmd.Short,
Alias: cmd.Aliases,
Parent: parent,
}
if cmd.HasFlags() {
cmd.Flags().VisitAll(func(f *pflag.Flag) {
if !f.Hidden {
command.Flags = append(command.Flags, flag{
Name: f.Name,
Shorthand: f.Shorthand,
Description: f.Usage,
})
}
})
}
if len(use) > 1 {
for _, a := range use[1:] {
a := regexp.MustCompile("[^a-zA-Z0-9]+").ReplaceAllString(a, "")
command.Arguments = append(command.Arguments, a)
}
}
if len(cmd.Commands()) > 0 {
for _, c := range cmd.Commands() {
command.SubCommands = append(command.SubCommands, cobraCommandConverterWithParent(c, &command))
}
}
return &command
}
return cobraCommandConverterWithParent(cmd, nil)
}