forked from izumin5210/grapi
/
main.go
96 lines (75 loc) 路 1.68 KB
/
main.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package gencmd
import (
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
// New creates an Executor instnace.
func New(
name string,
generateCmd *Command,
destroyCmd *Command,
opts ...Option,
) Executor {
ctx := defaultCtx()
ctx.apply(opts)
rootCmd := &cobra.Command{
Use: "grapi-gen-" + name,
}
setGenerateCommand(name, rootCmd, generateCmd, ctx)
setDestroyCommand(name, rootCmd, destroyCmd, ctx)
return newExecutor(ctx, rootCmd)
}
func setGenerateCommand(name string, rootCmd *cobra.Command, cmd *Command, ctx *Ctx) {
if cmd == nil {
return
}
ccmd := cmd.newCobraCommand()
ccmd.RunE = func(_ *cobra.Command, args []string) error {
app, err := ctx.CreateApp(cmd)
if err != nil {
return errors.WithStack(err)
}
app.UI.Section("Generate " + name)
params, err := cmd.BuildParams(cmd, args)
if err != nil {
return errors.WithStack(err)
}
err = app.Generator.Generate(params)
if err != nil {
return errors.WithStack(err)
}
return nil
}
if ccmd.Use == "" {
ccmd.Use = "generate"
}
cmd.ctx = ctx
rootCmd.AddCommand(ccmd)
}
func setDestroyCommand(name string, rootCmd *cobra.Command, cmd *Command, ctx *Ctx) {
if cmd == nil {
return
}
ccmd := cmd.newCobraCommand()
ccmd.RunE = func(_ *cobra.Command, args []string) error {
app, err := ctx.CreateApp(cmd)
if err != nil {
return errors.WithStack(err)
}
app.UI.Section("Destroy " + name)
params, err := cmd.BuildParams(cmd, args)
if err != nil {
return errors.WithStack(err)
}
err = app.Generator.Destroy(params)
if err != nil {
return errors.WithStack(err)
}
return nil
}
if ccmd.Use == "" {
ccmd.Use = "destroy"
}
cmd.ctx = ctx
rootCmd.AddCommand(ccmd)
}