-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spec.go
80 lines (68 loc) · 1.62 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
78
79
80
package spec
import (
"fmt"
"github.com/alecthomas/kingpin/v2"
"github.com/carapace-sh/carapace-spec/pkg/command"
"gopkg.in/yaml.v3"
)
func Register(app *kingpin.Application) {
cmd := app.GetCommand("_carapace")
if cmd == nil {
cmd = app.Command("_carapace", "")
cmd.Hidden()
}
specCmd := cmd.Command("spec", "")
specCmd.Action(func(pc *kingpin.ParseContext) error {
m, err := yaml.Marshal(Command(app))
if err != nil {
panic(err.Error())
}
fmt.Println(string(m))
return nil
})
}
func Command(app *kingpin.Application) command.Command {
return scrape(&kingpin.CmdModel{
Name: app.Name,
Help: app.Help,
FlagGroupModel: app.Model().FlagGroupModel,
CmdGroupModel: app.Model().CmdGroupModel,
}, true)
}
func scrape(c *kingpin.CmdModel, root bool) command.Command {
cmd := command.Command{
Name: c.Name,
Aliases: c.Aliases,
Description: c.Help,
Hidden: c.Hidden,
Commands: make([]command.Command, 0),
}
cmd.Completion.Flag = make(map[string][]string)
// TODO groups
for _, flag := range c.Flags {
f := command.Flag{
Longhand: "--" + flag.Name,
Value: !flag.IsBoolFlag(),
Usage: flag.Help,
Hidden: flag.Hidden,
Required: flag.Required,
Persistent: root,
}
if flag.Short != 0 {
f.Shorthand = "-" + string(flag.Short)
}
cmd.AddFlag(f)
if flag.IsBoolFlag() {
f.Longhand = "--no-" + flag.Name
f.Shorthand = ""
f.Hidden = true
cmd.AddFlag(f)
}
}
for _, subcmd := range c.Commands {
if subcmd.Name != "_carapace" {
cmd.Commands = append(cmd.Commands, scrape(subcmd, false))
}
}
return cmd
}