-
Notifications
You must be signed in to change notification settings - Fork 3
/
tagalign.go
459 lines (392 loc) · 9.84 KB
/
tagalign.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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
package tagalign
import (
"fmt"
"go/ast"
"go/token"
"log"
"reflect"
"sort"
"strconv"
"strings"
"github.com/fatih/structtag"
"golang.org/x/tools/go/analysis"
)
type Mode int
const (
StandaloneMode Mode = iota
GolangciLintMode
)
type Style int
const (
DefaultStyle Style = iota
StrictStyle
)
const (
errTagValueSyntax = "bad syntax for struct tag value"
)
func NewAnalyzer(options ...Option) *analysis.Analyzer {
return &analysis.Analyzer{
Name: "tagalign",
Doc: "check that struct tags are well aligned",
Run: func(p *analysis.Pass) (any, error) {
Run(p, options...)
return nil, nil
},
}
}
func Run(pass *analysis.Pass, options ...Option) []Issue {
var issues []Issue
for _, f := range pass.Files {
h := &Helper{
mode: StandaloneMode,
style: DefaultStyle,
align: true,
}
for _, opt := range options {
opt(h)
}
// StrictStyle must be used with WithAlign(true) and WithSort(...) together, or it will be ignored.
if h.style == StrictStyle && (!h.align || !h.sort) {
h.style = DefaultStyle
}
if !h.align && !h.sort {
// do nothing
return nil
}
ast.Inspect(f, func(n ast.Node) bool {
h.find(pass, n)
return true
})
h.Process(pass)
issues = append(issues, h.issues...)
}
return issues
}
type Helper struct {
mode Mode
style Style
align bool // whether enable tags align.
sort bool // whether enable tags sort.
fixedTagOrder []string // the order of tags, the other tags will be sorted by name.
singleFields []*ast.Field
consecutiveFieldsGroups [][]*ast.Field // fields in this group, must be consecutive in struct.
issues []Issue
}
// Issue is used to integrate with golangci-lint's inline auto fix.
type Issue struct {
Pos token.Position
Message string
InlineFix InlineFix
}
type InlineFix struct {
StartCol int // zero-based
Length int
NewString string
}
func (w *Helper) find(pass *analysis.Pass, n ast.Node) {
v, ok := n.(*ast.StructType)
if !ok {
return
}
fields := v.Fields.List
if len(fields) == 0 {
return
}
fs := make([]*ast.Field, 0)
split := func() {
n := len(fs)
if n > 1 {
w.consecutiveFieldsGroups = append(w.consecutiveFieldsGroups, fs)
} else if n == 1 {
w.singleFields = append(w.singleFields, fs[0])
}
fs = nil
}
for i, field := range fields {
if field.Tag == nil {
// field without tags
split()
continue
}
if i > 0 {
if fields[i-1].Tag == nil {
// if previous filed do not have a tag
fs = append(fs, field)
continue
}
preLineNum := pass.Fset.Position(fields[i-1].Tag.Pos()).Line
lineNum := pass.Fset.Position(field.Tag.Pos()).Line
if lineNum-preLineNum > 1 {
// fields with tags are not consecutive, including two case:
// 1. splited by lines
// 2. splited by a struct
split()
// check if the field is a struct
if _, ok := field.Type.(*ast.StructType); ok {
continue
}
}
}
fs = append(fs, field)
}
split()
}
func (w *Helper) report(pass *analysis.Pass, field *ast.Field, startCol int, msg, replaceStr string) {
if w.mode == GolangciLintMode {
iss := Issue{
Pos: pass.Fset.Position(field.Tag.Pos()),
Message: msg,
InlineFix: InlineFix{
StartCol: startCol,
Length: len(field.Tag.Value),
NewString: replaceStr,
},
}
w.issues = append(w.issues, iss)
}
if w.mode == StandaloneMode {
pass.Report(analysis.Diagnostic{
Pos: field.Tag.Pos(),
End: field.Tag.End(),
Message: msg,
SuggestedFixes: []analysis.SuggestedFix{
{
Message: msg,
TextEdits: []analysis.TextEdit{
{
Pos: field.Tag.Pos(),
End: field.Tag.End(),
NewText: []byte(replaceStr),
},
},
},
},
})
}
}
func (w *Helper) Process(pass *analysis.Pass) { //nolint:gocognit
// process grouped fields
for _, fields := range w.consecutiveFieldsGroups {
offsets := make([]int, len(fields))
var maxTagNum int
var tagsGroup, notSortedTagsGroup [][]*structtag.Tag
var uniqueKeys []string
addKey := func(k string) {
for _, key := range uniqueKeys {
if key == k {
return
}
}
uniqueKeys = append(uniqueKeys, k)
}
for i := 0; i < len(fields); {
field := fields[i]
column := pass.Fset.Position(field.Tag.Pos()).Column - 1
offsets[i] = column
tag, err := strconv.Unquote(field.Tag.Value)
if err != nil {
// if tag value is not a valid string, report it directly
w.report(pass, field, column, errTagValueSyntax, field.Tag.Value)
fields = removeField(fields, i)
continue
}
tags, err := structtag.Parse(tag)
if err != nil {
// if tag value is not a valid struct tag, report it directly
w.report(pass, field, column, err.Error(), field.Tag.Value)
fields = removeField(fields, i)
continue
}
maxTagNum = max(maxTagNum, tags.Len())
if w.sort {
cp := make([]*structtag.Tag, tags.Len())
for i, tag := range tags.Tags() {
cp[i] = tag
}
notSortedTagsGroup = append(notSortedTagsGroup, cp)
sortBy(w.fixedTagOrder, tags)
}
for _, t := range tags.Tags() {
addKey(t.Key)
}
tagsGroup = append(tagsGroup, tags.Tags())
i++
}
if w.sort && StrictStyle == w.style {
sortAllKeys(w.fixedTagOrder, uniqueKeys)
maxTagNum = len(uniqueKeys)
}
// record the max length of each column tag
type tagLen struct {
Key string // present only when sort enabled
Len int
}
tagMaxLens := make([]tagLen, maxTagNum)
for j := 0; j < maxTagNum; j++ {
var maxLength int
var key string
for i := 0; i < len(tagsGroup); i++ {
if w.style == StrictStyle {
key = uniqueKeys[j]
// search by key
for _, tag := range tagsGroup[i] {
if tag.Key == key {
maxLength = max(maxLength, len(tag.String()))
break
}
}
} else {
if len(tagsGroup[i]) <= j {
// in case of index out of range
continue
}
maxLength = max(maxLength, len(tagsGroup[i][j].String()))
}
}
tagMaxLens[j] = tagLen{key, maxLength}
}
for i, field := range fields {
tags := tagsGroup[i]
var newTagStr string
if w.align {
// if align enabled, align tags.
newTagBuilder := strings.Builder{}
for i, n := 0, 0; i < len(tags) && n < len(tagMaxLens); {
tag := tags[i]
var format string
if w.style == StrictStyle {
if tagMaxLens[n].Key == tag.Key {
// match
format = alignFormat(tagMaxLens[n].Len + 1) // with an extra space
newTagBuilder.WriteString(fmt.Sprintf(format, tag.String()))
i++
n++
} else {
// tag missing
format = alignFormat(tagMaxLens[n].Len + 1)
newTagBuilder.WriteString(fmt.Sprintf(format, ""))
n++
}
} else {
format = alignFormat(tagMaxLens[n].Len + 1) // with an extra space
newTagBuilder.WriteString(fmt.Sprintf(format, tag.String()))
i++
n++
}
}
newTagStr = newTagBuilder.String()
} else {
// otherwise check if tags order changed
if w.sort && reflect.DeepEqual(notSortedTagsGroup[i], tags) {
// if tags order not changed, do nothing
continue
}
tagsStr := make([]string, len(tags))
for i, tag := range tags {
tagsStr[i] = tag.String()
}
newTagStr = strings.Join(tagsStr, " ")
}
unquoteTag := strings.TrimRight(newTagStr, " ")
// unquoteTag := newTagStr
newTagValue := fmt.Sprintf("`%s`", unquoteTag)
if field.Tag.Value == newTagValue {
// nothing changed
continue
}
msg := "tag is not aligned, should be: " + unquoteTag
w.report(pass, field, offsets[i], msg, newTagValue)
}
}
// process single fields
for _, field := range w.singleFields {
column := pass.Fset.Position(field.Tag.Pos()).Column - 1
tag, err := strconv.Unquote(field.Tag.Value)
if err != nil {
w.report(pass, field, column, errTagValueSyntax, field.Tag.Value)
continue
}
tags, err := structtag.Parse(tag)
if err != nil {
w.report(pass, field, column, err.Error(), field.Tag.Value)
continue
}
originalTags := append([]*structtag.Tag(nil), tags.Tags()...)
if w.sort {
sortBy(w.fixedTagOrder, tags)
}
newTagValue := fmt.Sprintf("`%s`", tags.String())
if reflect.DeepEqual(originalTags, tags.Tags()) && field.Tag.Value == newTagValue {
// if tags order not changed, do nothing
continue
}
msg := "tag is not aligned , should be: " + tags.String()
w.report(pass, field, column, msg, newTagValue)
}
}
// Issues returns all issues found by the analyzer.
// It is used to integrate with golangci-lint.
func (w *Helper) Issues() []Issue {
log.Println("tagalign 's Issues() should only be called in golangci-lint mode")
return w.issues
}
// sortBy sorts tags by fixed order.
// If a tag is not in the fixed order, it will be sorted by name.
func sortBy(fixedOrder []string, tags *structtag.Tags) {
// sort by fixed order
sort.Slice(tags.Tags(), func(i, j int) bool {
ti := tags.Tags()[i]
tj := tags.Tags()[j]
oi := findIndex(fixedOrder, ti.Key)
oj := findIndex(fixedOrder, tj.Key)
if oi == -1 && oj == -1 {
return ti.Key < tj.Key
}
if oi == -1 {
return false
}
if oj == -1 {
return true
}
return oi < oj
})
}
func sortAllKeys(fixedOrder []string, keys []string) {
sort.Slice(keys, func(i, j int) bool {
oi := findIndex(fixedOrder, keys[i])
oj := findIndex(fixedOrder, keys[j])
if oi == -1 && oj == -1 {
return keys[i] < keys[j]
}
if oi == -1 {
return false
}
if oj == -1 {
return true
}
return oi < oj
})
}
func findIndex(s []string, e string) int {
for i, a := range s {
if a == e {
return i
}
}
return -1
}
func alignFormat(length int) string {
return "%" + fmt.Sprintf("-%ds", length)
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func removeField(fields []*ast.Field, index int) []*ast.Field {
if index < 0 || index >= len(fields) {
return fields
}
return append(fields[:index], fields[index+1:]...)
}