-
Notifications
You must be signed in to change notification settings - Fork 0
/
spec.go
70 lines (63 loc) · 1.42 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
package spec
import (
"fmt"
"github.com/carapace-sh/carapace-spec/pkg/command"
"github.com/urfave/cli/v2"
"gopkg.in/yaml.v2"
)
func Register(app *cli.App) {
app.Commands = append(app.Commands, &cli.Command{
Name: "_carapace",
Hidden: true,
Subcommands: []*cli.Command{
{
Name: "spec",
Action: func(ctx *cli.Context) (err error) {
var m []byte
if m, err = yaml.Marshal(Command(app)); err == nil {
fmt.Println(string(m))
}
return
},
},
},
})
}
func Command(app *cli.App) command.Command {
return scrape(&cli.Command{
Name: app.Name,
Description: app.Usage,
Flags: app.Flags,
Subcommands: app.Commands,
})
}
func scrape(c *cli.Command) command.Command {
cmd := command.Command{
Name: c.Name,
Aliases: c.Aliases,
Description: c.Usage,
Hidden: c.Hidden,
Group: c.Category,
Flags: make(map[string]string),
Commands: make([]command.Command, 0),
}
cmd.Completion.Flag = make(map[string][]string)
for _, f := range c.Flags {
flag := flag{f}
cmd.AddFlag(command.Flag{
Longhand: "--" + flag.Name(),
Shorthand: flag.Shorthand(),
Usage: flag.Usage(),
Value: flag.TakesValue(),
})
if flag.TakesFile() {
cmd.Completion.Flag[flag.Name()] = []string{"$files"}
}
}
for _, subcmd := range c.Subcommands {
if !subcmd.Hidden {
cmd.Commands = append(cmd.Commands, scrape(subcmd))
}
}
return cmd
}