forked from swaggo/swag
-
Notifications
You must be signed in to change notification settings - Fork 0
/
formater.go
326 lines (285 loc) · 7.93 KB
/
formater.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
package swag
import (
"bytes"
"crypto/md5"
"fmt"
"go/ast"
goparser "go/parser"
"go/token"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
"text/tabwriter"
)
const splitTag = "&*"
// Formater implements a formater for Go source files.
type Formater struct {
// debugging output goes here
debug Debugger
// excludes excludes dirs and files in SearchDir
excludes map[string]struct{}
mainFile string
}
// NewFormater create a new formater instance.
func NewFormater() *Formater {
formater := &Formater{
debug: log.New(os.Stdout, "", log.LstdFlags),
excludes: make(map[string]struct{}),
}
return formater
}
// FormatAPI format the swag comment.
func (f *Formater) FormatAPI(searchDir, excludeDir, mainFile string) error {
searchDirs := strings.Split(searchDir, ",")
for _, searchDir := range searchDirs {
if _, err := os.Stat(searchDir); os.IsNotExist(err) {
return fmt.Errorf("dir: %s does not exist", searchDir)
}
}
for _, fi := range strings.Split(excludeDir, ",") {
fi = strings.TrimSpace(fi)
if fi != "" {
fi = filepath.Clean(fi)
f.excludes[fi] = struct{}{}
}
}
// parse main.go
absMainAPIFilePath, err := filepath.Abs(filepath.Join(searchDirs[0], mainFile))
if err != nil {
return err
}
err = f.FormatMain(absMainAPIFilePath)
if err != nil {
return err
}
f.mainFile = mainFile
err = f.formatMultiSearchDir(searchDirs)
if err != nil {
return err
}
return nil
}
func (f *Formater) formatMultiSearchDir(searchDirs []string) error {
for _, searchDir := range searchDirs {
f.debug.Printf("Format API Info, search dir:%s", searchDir)
err := filepath.Walk(searchDir, f.visit)
if err != nil {
return err
}
}
return nil
}
func (f *Formater) visit(path string, fileInfo os.FileInfo, err error) error {
if err := walkWith(f.excludes, false)(path, fileInfo); err != nil {
return err
} else if fileInfo.IsDir() {
// skip if file is folder
return nil
}
if strings.HasSuffix(strings.ToLower(path), "_test.go") || filepath.Ext(path) != ".go" {
// skip if file not has suffix "*.go"
return nil
}
if strings.HasSuffix(strings.ToLower(path), f.mainFile) {
// skip main file
return nil
}
err = f.FormatFile(path)
if err != nil {
return fmt.Errorf("ParseFile error:%+v", err)
}
return nil
}
// FormatMain format the main.go comment.
func (f *Formater) FormatMain(mainFilepath string) error {
fileSet := token.NewFileSet()
astFile, err := goparser.ParseFile(fileSet, mainFilepath, nil, goparser.ParseComments)
if err != nil {
return fmt.Errorf("cannot format file, err: %w path : %s ", err, mainFilepath)
}
var (
formatedComments = bytes.Buffer{}
// CommentCache
oldCommentsMap = make(map[string]string)
)
if astFile.Comments != nil {
for _, comment := range astFile.Comments {
formatFuncDoc(comment.List, &formatedComments, oldCommentsMap)
}
}
return writeFormatedComments(mainFilepath, formatedComments, oldCommentsMap)
}
// FormatFile format the swag comment in go function.
func (f *Formater) FormatFile(filepath string) error {
fileSet := token.NewFileSet()
astFile, err := goparser.ParseFile(fileSet, filepath, nil, goparser.ParseComments)
if err != nil {
return fmt.Errorf("cannot format file, err: %w path : %s ", err, filepath)
}
var (
formatedComments = bytes.Buffer{}
// CommentCache
oldCommentsMap = make(map[string]string)
)
for _, astDescription := range astFile.Decls {
astDeclaration, ok := astDescription.(*ast.FuncDecl)
if ok && astDeclaration.Doc != nil && astDeclaration.Doc.List != nil {
formatFuncDoc(astDeclaration.Doc.List, &formatedComments, oldCommentsMap)
}
}
return writeFormatedComments(filepath, formatedComments, oldCommentsMap)
}
func writeFormatedComments(filepath string, formatedComments bytes.Buffer, oldCommentsMap map[string]string) error {
// Replace the file
// Read the file
srcBytes, err := ioutil.ReadFile(filepath)
if err != nil {
return fmt.Errorf("cannot open file, err: %w path : %s ", err, filepath)
}
replaceSrc := string(srcBytes)
newComments := strings.Split(formatedComments.String(), "\n")
for _, e := range newComments {
commentSplit := strings.Split(e, splitTag)
if len(commentSplit) == 2 {
commentHash, commentContent := commentSplit[0], commentSplit[1]
if !isBlankComment(commentContent) {
replaceSrc = strings.Replace(replaceSrc, oldCommentsMap[commentHash], commentContent, 1)
}
}
}
return writeBack(filepath, []byte(replaceSrc), srcBytes)
}
func formatFuncDoc(commentList []*ast.Comment, formatedComments io.Writer, oldCommentsMap map[string]string) {
tabw := tabwriter.NewWriter(formatedComments, 0, 0, 2, ' ', 0)
for _, comment := range commentList {
commentLine := comment.Text
if isSwagComment(commentLine) || isBlankComment(commentLine) {
cmd5 := fmt.Sprintf("%x", md5.Sum([]byte(commentLine)))
// Find the separator and replace to \t
c := separatorFinder(commentLine, '\t')
oldCommentsMap[cmd5] = commentLine
// md5 + splitTag + srcCommentLine
// eg. xxx&*@Description get struct array
_, _ = fmt.Fprintln(tabw, cmd5+splitTag+c)
}
}
// format by tabwriter
_ = tabw.Flush()
}
// Check of @Param @Success @Failure @Response @Header
var specialTagForSplit = map[string]byte{
paramAttr: 1,
successAttr: 1,
failureAttr: 1,
responseAttr: 1,
headerAttr: 1,
}
var skipChar = map[byte]byte{
'"': 1,
'(': 1,
'{': 1,
'[': 1,
}
var skipCharEnd = map[byte]byte{
'"': 1,
')': 1,
'}': 1,
']': 1,
}
func separatorFinder(comment string, rp byte) string {
commentBytes := []byte(comment)
commentLine := strings.TrimSpace(strings.TrimLeft(comment, "/"))
if len(commentLine) == 0 {
return ""
}
attribute := strings.Fields(commentLine)[0]
attrLen := strings.Index(comment, attribute) + len(attribute)
attribute = strings.ToLower(attribute)
var i = attrLen
if _, ok := specialTagForSplit[attribute]; ok {
var skipFlag bool
for ; i < len(commentBytes); i++ {
if !skipFlag && commentBytes[i] == ' ' {
j := i
for j < len(commentBytes) && commentBytes[j] == ' ' {
j++
}
commentBytes = replaceRange(commentBytes, i, j, rp)
}
if _, ok := skipChar[commentBytes[i]]; ok && !skipFlag {
skipFlag = true
} else if _, ok := skipCharEnd[commentBytes[i]]; ok && skipFlag {
skipFlag = false
}
}
} else {
for i < len(commentBytes) && commentBytes[i] == ' ' {
i++
}
if i >= len(commentBytes) {
return comment
}
commentBytes = replaceRange(commentBytes, attrLen, i, rp)
}
return string(commentBytes)
}
func replaceRange(s []byte, start, end int, new byte) []byte {
if start > end || end < 1 {
return s
}
if end > len(s) {
end = len(s)
}
s = append(s[:start], s[end-1:]...)
s[start] = new
return s
}
var swagCommentExpression = regexp.MustCompile("@[A-z]+")
func isSwagComment(comment string) bool {
return swagCommentExpression.MatchString(strings.ToLower(comment))
}
func isBlankComment(comment string) bool {
lc := strings.TrimSpace(comment)
return len(lc) == 0
}
// writeBack write to file
func writeBack(filepath string, src, old []byte) error {
// make a temporary backup before overwriting original
bakname, err := backupFile(filepath+".", old, 0644)
if err != nil {
return err
}
err = ioutil.WriteFile(filepath, src, 0644)
if err != nil {
_ = os.Rename(bakname, filepath)
return err
}
_ = os.Remove(bakname)
return nil
}
const chmodSupported = runtime.GOOS != "windows"
// backupFile writes data to a new file named filename<number> with permissions perm,
// with <number randomly chosen such that the file name is unique. backupFile returns
// the chosen file name.
// copy from golang/cmd/gofmt
func backupFile(filename string, data []byte, perm os.FileMode) (string, error) {
// create backup file
f, err := ioutil.TempFile(filepath.Dir(filename), filepath.Base(filename))
if err != nil {
return "", err
}
if chmodSupported {
_ = f.Chmod(perm)
}
// write data to backup file
_, err = f.Write(data)
if err1 := f.Close(); err == nil {
err = err1
}
return f.Name(), err
}