-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd.go
120 lines (103 loc) · 2.65 KB
/
cmd.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package command
import (
"fmt"
"path/filepath"
"github.com/AlecAivazis/survey/v2"
"github.com/pkg/errors"
"github.com/y19941115mx/ygo/framework/cobra"
"github.com/y19941115mx/ygo/framework/contract"
"github.com/y19941115mx/ygo/framework/util"
)
// 初始化command相关命令
func initCmdCommand() *cobra.Command {
cmdCommand.AddCommand(cmdListCommand)
cmdCommand.AddCommand(cmdCreateCommand)
return cmdCommand
}
// 二级命令
var cmdCommand = &cobra.Command{
Use: "command",
Short: "控制台命令相关",
RunE: func(c *cobra.Command, args []string) error {
if len(args) == 0 {
c.Help()
}
return nil
},
}
// cmdListCommand 列出所有的控制台命令
var cmdListCommand = &cobra.Command{
Use: "list",
Short: "列出所有控制台命令",
RunE: func(c *cobra.Command, args []string) error {
cmds := c.Root().Commands()
ps := [][]string{}
for _, cmd := range cmds {
line := []string{cmd.Name(), cmd.Short}
ps = append(ps, line)
}
util.PrettyPrint(ps)
return nil
},
}
// cmdCreateCommand 创建一个业务控制台命令
var cmdCreateCommand = &cobra.Command{
Use: "new",
Aliases: []string{"create", "init"}, // 设置别名为 create init
Short: "创建一个控制台命令",
RunE: func(c *cobra.Command, args []string) error {
container := c.GetContainer()
fmt.Println("开始创建控制台命令...")
var name string
var folder string
{
prompt := &survey.Input{
Message: "请输入控制台命令名称:",
}
err := survey.AskOne(prompt, &name)
if err != nil {
return err
}
}
{
prompt := &survey.Input{
Message: "请输入文件夹名称(默认: 同控制台命令):",
}
err := survey.AskOne(prompt, &folder)
if err != nil {
return err
}
}
if folder == "" {
folder = name
}
app := container.MustMake(contract.AppKey).(contract.App)
pFolder := filepath.Join(app.CommandFolder(), folder)
if err := util.CreateFileTemlate(true, pFolder, name+".go", cmdTmpl, name); err != nil {
return errors.Cause(err)
}
fmt.Println("创建新命令行工具成功,路径:", filepath.Join(pFolder, name+".go"))
fmt.Println("请记得完成后将命令行挂载到 " + filepath.Join(app.CommandFolder(), "kernel.go"))
return nil
},
}
// 命令行工具模版
var cmdTmpl string = `package {{.}}
import (
"fmt"
"github.com/y19941115mx/ygo/framework/cobra"
)
// 初始化命令
func init{{.|title}}Command() *cobra.Command {
return {{.}}Command
}
var {{.}}Command = &cobra.Command{
Use: "{{.}}",
Short: "{{.}}",
RunE: func(c *cobra.Command, args []string) error {
container := c.GetContainer()
fmt.Println(container)
return nil
},
}
`