-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spec.go
77 lines (66 loc) · 1.66 KB
/
spec.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
package spec
import (
"fmt"
"strings"
"github.com/alecthomas/kong"
"github.com/carapace-sh/carapace-spec/pkg/command"
"gopkg.in/yaml.v3"
)
type spec struct{}
func (s spec) Run(ctx *kong.Context) (err error) {
var m []byte
if m, err = yaml.Marshal(Command(ctx.Model.Node)); err == nil {
fmt.Fprintln(ctx.Stdout, string(m))
}
return
}
type Plugin struct {
Carapace struct {
Spec spec `cmd:"" name:"spec"`
} `cmd:"" name:"_carapace" hidden:""`
}
func Command(node *kong.Node) command.Command {
cmd := command.Command{
Name: node.Name,
Aliases: node.Aliases,
Description: node.Help,
Commands: make([]command.Command, 0),
}
cmd.Completion.Flag = make(map[string][]string)
if group := node.Group; group != nil {
cmd.Group = group.Key
}
for _, flag := range node.Flags {
f := command.Flag{
Longhand: "--" + flag.Name,
Value: !flag.IsBool(),
Repeatable: flag.IsCounter() || flag.IsCumulative(),
Required: flag.Required,
Usage: flag.Help,
}
if flag.Short != 0 {
f.Shorthand = "-" + string(flag.Short)
}
cmd.AddFlag(f)
if flag.Enum != "" {
splitted := strings.Split(flag.Enum, ",")
for index, v := range splitted {
splitted[index] = strings.TrimSpace(v)
}
cmd.Completion.Flag[flag.Name] = splitted
} else if tag := flag.Flag.Tag; tag != nil {
switch tag.Type {
case "path", "existingfile":
cmd.Completion.Flag[flag.Name] = []string{"$files"}
case "existingdir":
cmd.Completion.Flag[flag.Name] = []string{"$directories"}
}
}
}
for _, subcmd := range node.Children {
if !subcmd.Hidden {
cmd.Commands = append(cmd.Commands, Command(subcmd))
}
}
return cmd
}