-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathginhelper.go
215 lines (204 loc) · 5.39 KB
/
ginhelper.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
package main
import (
"bytes"
"fmt"
"go/format"
"io/ioutil"
"os"
"os/exec"
"path"
"regexp"
"strings"
"text/template"
"github.com/5bug/ginhelper/templates"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
// CreateApp create an app
func CreateApp(rootDir, project, appName string) (err error) {
app := App{
Project: project,
Name: strings.ToLower(appName),
Service: cases.Title(language.Und, cases.NoLower).String(appName),
RootDir: rootDir,
APIDir: path.Join(rootDir, fmt.Sprintf("internal/%s/api", strings.ToLower(appName))),
}
for k, v := range appfiles {
destFile := path.Join(app.RootDir, fmt.Sprintf(k, app.Name))
if ok, _ := PathExists(destFile); !ok {
if err = writeOneFile(app, v, destFile); err != nil {
return
}
} else {
logrus.Warnf("file[%s] is exists", destFile)
}
}
if ok, _ := PathExists("pkg"); !ok {
if err = RestoreAssets(app.RootDir, "pkg"); err != nil {
return
}
}
if err = UpdateAPI(rootDir, project, appName); err != nil {
return
}
return
}
// AppExist app exist
func AppExist(rootDir, appName string) (ok bool) {
addDir := path.Join(rootDir, fmt.Sprintf("cmd/%s", strings.ToLower(appName)))
ok, _ = PathExists(addDir)
return
}
// UpdateAPI update api
func UpdateAPI(rootDir, project, appName string) (err error) {
app := App{
Project: project,
Name: strings.ToLower(appName),
Service: strings.ReplaceAll(cases.Title(language.Und, cases.NoLower).String(appName), "-", ""),
RootDir: rootDir,
APIDir: path.Join(rootDir, fmt.Sprintf("internal/%s/api", strings.ToLower(appName))),
}
requestMap, err := readRequests(app.APIDir)
if err != nil {
return
}
value := RenderValue{
App: app,
Requests: requestMap.Requests(),
}
// 创建handlers.go
if err = writeOneFile(value, templates.HandlersTpl, path.Join(app.APIDir, "handlers.go")); err != nil {
return
}
// 创建router.go
if err = writeOneFile(value, templates.RouterTpl, path.Join(app.APIDir, "router.go")); err != nil {
return
}
// 创建service文件
for group, requests := range requestMap {
value = RenderValue{
App: app,
Requests: requests,
}
destFile := path.Join(app.RootDir, fmt.Sprintf("/internal/%s/service/%s.go", app.Name, group))
if ok, _ := PathExists(destFile); !ok {
if err = writeOneFile(value, templates.SvcFullTpl, destFile); err != nil {
return
}
} else {
if err = patchService(&value, templates.SvcFuncTpl, destFile); err != nil {
return
}
}
}
return nil
}
// InitProject init project
func InitProject(project string) error {
cmd := exec.Command("/bin/sh", "-c", fmt.Sprintf("go mod init %s", project))
_, err := cmd.CombinedOutput()
return err
}
func readRequests(apiPath string) (requestMap RequestMap, err error) {
var data []byte
files, err := ioutil.ReadDir(apiPath)
if err != nil {
return
}
requestMap = make(RequestMap)
for _, file := range files {
if strings.EqualFold(file.Name(), "router.go") || strings.EqualFold(file.Name(), "handlers.go") {
continue
}
apiFile := path.Join(apiPath, file.Name())
if path.Ext(apiFile) != ".go" {
continue
}
group := strings.ReplaceAll(file.Name(), ".go", "")
data, err = ioutil.ReadFile(apiFile)
if err != nil {
logrus.Infof("file[%s]read file error:%v", file.Name(), err)
continue
}
str := "//\\s(.*?)Request\\s(.*?)\n//\\s@Router\\s(.*?)\\s\\[(.*?)\\]\n//\\s@Auth\\s(.*?)\n"
r := regexp.MustCompile(str)
params := r.FindAllStringSubmatch(string(data), -1)
if len(params) <= 0 {
logrus.Infof("file[%s]cannot match method", file.Name())
continue
}
requests, ok := requestMap[group]
if !ok {
requests = []APIRequest{}
}
for _, p := range params {
requests = append(requests, APIRequest{
Group: group,
Name: p[1],
Comment: p[2],
Route: p[3],
Method: strings.ToUpper(p[4]),
Auth: ParseBool(p[5]),
})
}
requestMap[group] = requests
}
return
}
func render(value interface{}, tplData string) ([]byte, error) {
tmpl, err := template.New("value").Parse(tplData)
if err != nil {
return nil, err
}
var buf bytes.Buffer
err = tmpl.ExecuteTemplate(&buf, "value", value)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func writeOneFile(value interface{}, tplData string, destFile string) error {
data, err := render(value, tplData)
if err != nil {
return errors.Wrap(err, destFile)
}
if data, err = format.Source(data); err != nil {
return err
}
if err = os.MkdirAll(path.Dir(destFile), os.ModePerm); err != nil {
return err
}
if err = ioutil.WriteFile(destFile, data, 0666); err != nil {
return err
}
return nil
}
func patchService(value *RenderValue, tplData string, destFile string) error {
oldData, err := ioutil.ReadFile(destFile)
if err != nil {
return err
}
bs := [][]byte{oldData}
for _, request := range value.Requests {
str := fmt.Sprintf("func \\(s \\*Service\\) %s\\(ctx \\*rest\\.Context, request \\*api\\.%sRequest\\) \\(reply \\*api.%sReply, err error\\)",
request.Name, request.Name, request.Name)
r := regexp.MustCompile(str)
if !r.Match(oldData) {
data, err := render(request, tplData)
if err != nil {
return err
}
bs = append(bs, data)
}
}
newData := bytes.Join(bs, []byte("\n\n"))
if newData, err = format.Source(newData); err != nil {
return err
}
if err = ioutil.WriteFile(destFile, newData, 0666); err != nil {
return err
}
return nil
}