/
project.go
352 lines (299 loc) · 6.94 KB
/
project.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package project
import (
"bytes"
"fmt"
"github.com/AlecAivazis/survey/v2"
"github.com/pkg/errors"
"go/format"
"io/fs"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"text/template"
"github.com/yoas0bi/micro-toolkit/utils/cli"
"gopkg.in/yaml.v3"
"embed"
)
//go:embed templates/*
var templates embed.FS
const PROJECT_SETTING_FILE_PATH = ".mcube.yaml"
// LoadConfigFromCLI 配置
func LoadConfigFromCLI() (*Project, error) {
p := &Project{
render: template.New("project"),
createdDir: map[string]bool{},
}
p.render.Funcs(p.FuncMap())
err := survey.AskOne(
&survey.Input{
Message: "请输入项目包名称:",
Default: "github.com/yoas0bi/demo",
},
&p.PKG,
survey.WithValidator(survey.Required),
)
if err != nil {
return nil, err
}
err = survey.AskOne(
&survey.Input{
Message: "请输入项目描述:",
Default: "",
},
&p.Description,
survey.WithValidator(survey.Required),
)
if err != nil {
return nil, err
}
// 选择是否接入权限中心Keyauth
enableKeyauth := &survey.Confirm{
Message: "是否接入权限中心[keyauth]",
}
err = survey.AskOne(enableKeyauth, &p.EnableKeyauth)
if err != nil {
return nil, err
}
if p.EnableKeyauth {
p.LoadKeyauthConfig()
}
// 选择使用的存储
choicedDB := ""
choiceDB := &survey.Select{
Message: "选择数据库类型:",
Options: []string{"MySQL", "MongoDB"},
Default: "MySQL",
}
err = survey.AskOne(choiceDB, &choicedDB)
if err != nil {
return nil, err
}
switch choicedDB {
case "MySQL":
p.EnableMySQL = true
p.LoadMySQLConfig()
case "MongoDB":
p.EnableMongoDB = true
p.LoadMongoDBConfig()
}
// 选择是否生成样例
genExample := &survey.Confirm{
Message: "生成样例代码",
}
survey.AskOne(genExample, &p.GenExample)
if p.GenExample {
// 选择使用的HTTP 框架
choiceFW := &survey.Select{
Message: "选择HTTP框架:",
Options: []string{"go-restful", "gin", "httprouter"},
Default: "go-restful",
}
err = survey.AskOne(choiceFW, &p.HttpFramework)
if err != nil {
return nil, err
}
}
p.caculate()
return p, nil
}
func LoadProjectFromYAML(path string) (*Project, error) {
fp, err := os.Open(path)
if err != nil {
return nil, err
}
defer fp.Close()
p := &Project{}
err = yaml.NewDecoder(fp).Decode(p)
if err != nil {
return nil, err
}
return p, nil
}
// Project todo
type Project struct {
PKG string `yaml:"pkg"`
Name string `yaml:"name"`
Description string `yaml:"description"`
EnableKeyauth bool `yaml:"enable_keyauth"`
Keyauth *Keyauth `yaml:"-"`
EnableMySQL bool `yaml:"enable_mysql"`
MySQL *MySQL `yaml:"-"`
EnableMongoDB bool `yaml:"enable_mongodb"`
MongoDB *MongoDB `yaml:"-"`
GenExample bool `yaml:"gen_example"`
HttpFramework string `yaml:"http_framework"`
EnableCache bool `yaml:"enable_cache"`
render *template.Template
createdDir map[string]bool
}
// Keyauth 鉴权服务配置
type Keyauth struct {
Host string
Port string
ClientID string
ClientSecret string
}
type MySQL struct {
Host string
Port string
Database string
UserName string
Password string
}
type MongoDB struct {
Endpoints []string
UserName string
Password string
Database string
AuthDB string
}
func (p *Project) caculate() {
if p.PKG != "" {
slice := strings.Split(p.PKG, "/")
p.Name = slice[len(slice)-1]
}
}
func (p *Project) ToYAML() (string, error) {
b, err := yaml.Marshal(p)
if err != nil {
return "", err
}
return string(b), nil
}
func (p *Project) SaveFile(filePath string) error {
f, err := os.Create(filePath)
if err != nil {
return err
}
defer f.Close()
content, err := p.ToYAML()
if err != nil {
return err
}
_, err = f.WriteString(content)
return err
}
// Init 初始化项目
func (p *Project) Init() error {
fn := func(path string, d fs.DirEntry, _ error) error {
// 不处理目录
if d.IsDir() {
return nil
}
// 处理是否生成样例代码
if p.GenExample {
if strings.Contains(path, "apps/book") {
// 只生成对应框架的样例代码
if strings.Contains(path, "apps/book/api") && p.HttpFramework != "" {
if !strings.HasSuffix(path, fmt.Sprintf(".%s.tpl", p.HttpFramework)) {
return nil
}
}
}
if strings.Contains(path, "protocol/http.go") && p.HttpFramework != "" {
if !strings.HasSuffix(path, fmt.Sprintf(".%s.tpl", p.HttpFramework)) {
return nil
}
}
} else {
return nil
}
// 如果不是使用MySQL, 不需要渲染的文件
if strings.Contains(path, "apps/book/impl/sql") && !p.EnableMySQL {
return nil
}
// 忽略不是模板的文件
if !strings.HasSuffix(d.Name(), ".tpl") {
return nil
}
// 读取模板内容
data, err := templates.ReadFile(path)
if err != nil {
return err
}
// 替换templates为项目目录名称
target := strings.Replace(path, "templates", p.Name, 1)
dirName := filepath.Dir(target)
// 去除模版后缀
sourceFileName := strings.TrimSuffix(filepath.Base(target), ".tpl")
if p.HttpFramework != "" {
// 去除框架后缀
sourceFileName = strings.TrimSuffix(sourceFileName, "."+p.HttpFramework)
}
return p.rendTemplate(dirName, sourceFileName, string(data))
}
err := fs.WalkDir(templates, "templates", fn)
if err != nil {
return err
}
// 保存项目设置文件
err = p.SaveFile(path.Join(p.Name, PROJECT_SETTING_FILE_PATH))
if err != nil {
fmt.Printf("保存项目配置文件: %s 失败: %s\n", PROJECT_SETTING_FILE_PATH, err)
}
fmt.Println("项目初始化完成, 项目结构如下: ")
if err := p.show(); err != nil {
return err
}
return nil
}
func (p *Project) show() error {
return cli.Tree(os.Stdout, p.Name, true)
}
func (p *Project) dirNotExist(path string) bool {
if _, ok := p.createdDir[path]; ok {
return false
}
return true
}
func (p *Project) rendTemplate(dir, file, tmpl string) error {
if dir != "" {
if p.dirNotExist(dir) {
err := os.MkdirAll(dir, os.ModePerm)
if err != nil {
return err
}
p.createdDir[dir] = true
}
}
filePath := ""
if dir != "" {
filePath = dir + "/" + file
} else {
filePath = file
}
t, err := p.render.Parse(tmpl)
if err != nil {
return fmt.Errorf("render %s/%s error, %s", dir, file, err)
}
buf := bytes.NewBufferString("")
err = t.Execute(buf, p)
if err != nil {
return errors.Wrapf(err, "template data err")
}
var content []byte
if path.Ext(file) == "go" {
code, err := format.Source(buf.Bytes())
if err != nil {
return errors.Wrapf(err, "format %s code err", file)
}
content = code
} else {
content = buf.Bytes()
}
return ioutil.WriteFile(filePath, content, 0644)
}
func (p *Project) FuncMap() template.FuncMap {
return template.FuncMap{
// []string ==> ["xxx", "xxx"]
"ListToTOML": func(strs []string) string {
strList := []string{}
for i := range strs {
strList = append(strList, fmt.Sprintf(`"%s"`, strs[i]))
}
return "[" + strings.Join(strList, ",") + "]"
},
}
}